├── .gitignore
├── LICENSE
├── Notice.txt
├── README.md
├── VERL_README.md
├── docs
├── experiment_log.md
├── multinode.md
└── retriever.md
├── example
├── case.txt
├── corpus.jsonl
├── multinode
│ ├── train_grpo_multinode_32b.sh
│ ├── train_grpo_multinode_72b.sh
│ └── train_ppo_multinode_32b.sh
└── retriever
│ ├── retrieval_launch_ann.sh
│ ├── retrieval_launch_bm25.sh
│ ├── retrieval_launch_google.sh
│ ├── retrieval_launch_hierarchical.sh
│ └── retrieval_launch_serpapi.sh
├── infer.py
├── public
├── head.png
├── llama32-3b.png
├── logo.png
├── main.png
├── multi-turn.png
├── single-turn.png
├── status.png
└── worker.png
├── pyproject.toml
├── requirements.txt
├── retrieval_launch.sh
├── scripts
├── data_process
│ ├── nq.py
│ ├── nq_rag.py
│ ├── nq_search.py
│ ├── qa_search_test_merge.py
│ └── qa_search_train_merge.py
├── download.py
├── download.sh
├── nq_hotpotqa
│ ├── README.md
│ ├── data_process.sh
│ ├── evaluate.sh
│ ├── v0.1
│ │ ├── train_grpo.sh
│ │ └── train_ppo.sh
│ ├── v0.2
│ │ ├── train_grpo.sh
│ │ └── train_ppo.sh
│ └── v0.3
│ │ ├── train_grpo_format.sh
│ │ └── train_ppo_format.sh
├── upload.py
└── upload.sh
├── search_r1
├── __init__.py
├── llm_agent
│ ├── __init__.py
│ ├── generation.py
│ └── tensor_helper.py
└── search
│ ├── build_index.sh
│ ├── google_search_server.py
│ ├── index_builder.py
│ ├── rerank_server.py
│ ├── retrieval.py
│ ├── retrieval.sh
│ ├── retrieval_request.py
│ ├── retrieval_rerank_server.py
│ ├── retrieval_server.py
│ └── serp_search_server.py
├── setup.py
├── train_grpo.sh
├── train_ppo.sh
└── verl
├── __init__.py
├── models
├── README.md
├── __init__.py
├── llama
│ ├── __init__.py
│ └── megatron
│ │ ├── __init__.py
│ │ ├── checkpoint_utils
│ │ ├── __init__.py
│ │ ├── llama_loader.py
│ │ └── llama_saver.py
│ │ ├── layers
│ │ ├── __init__.py
│ │ ├── parallel_attention.py
│ │ ├── parallel_decoder.py
│ │ ├── parallel_linear.py
│ │ ├── parallel_mlp.py
│ │ └── parallel_rmsnorm.py
│ │ └── modeling_llama_megatron.py
├── registry.py
├── transformers
│ ├── __init__.py
│ ├── llama.py
│ ├── monkey_patch.py
│ └── qwen2.py
└── weight_loader_registry.py
├── protocol.py
├── single_controller
├── __init__.py
├── base
│ ├── __init__.py
│ ├── decorator.py
│ ├── megatron
│ │ ├── __init__.py
│ │ ├── worker.py
│ │ └── worker_group.py
│ ├── register_center
│ │ ├── __init__.py
│ │ └── ray.py
│ ├── worker.py
│ └── worker_group.py
├── ray
│ ├── __init__.py
│ ├── base.py
│ └── megatron.py
└── version
│ └── version
├── third_party
├── __init__.py
└── vllm
│ ├── __init__.py
│ ├── vllm_v_0_3_1
│ ├── __init__.py
│ ├── arg_utils.py
│ ├── config.py
│ ├── llm.py
│ ├── llm_engine_sp.py
│ ├── model_loader.py
│ ├── model_runner.py
│ ├── parallel_state.py
│ ├── tokenizer.py
│ ├── weight_loaders.py
│ └── worker.py
│ ├── vllm_v_0_4_2
│ ├── __init__.py
│ ├── arg_utils.py
│ ├── config.py
│ ├── dtensor_weight_loaders.py
│ ├── hf_weight_loader.py
│ ├── llm.py
│ ├── llm_engine_sp.py
│ ├── megatron_weight_loaders.py
│ ├── model_loader.py
│ ├── model_runner.py
│ ├── parallel_state.py
│ ├── spmd_gpu_executor.py
│ ├── tokenizer.py
│ └── worker.py
│ ├── vllm_v_0_5_4
│ ├── __init__.py
│ ├── arg_utils.py
│ ├── config.py
│ ├── dtensor_weight_loaders.py
│ ├── hf_weight_loader.py
│ ├── llm.py
│ ├── llm_engine_sp.py
│ ├── megatron_weight_loaders.py
│ ├── model_loader.py
│ ├── model_runner.py
│ ├── parallel_state.py
│ ├── spmd_gpu_executor.py
│ ├── tokenizer.py
│ └── worker.py
│ └── vllm_v_0_6_3
│ ├── __init__.py
│ ├── arg_utils.py
│ ├── config.py
│ ├── dtensor_weight_loaders.py
│ ├── hf_weight_loader.py
│ ├── llm.py
│ ├── llm_engine_sp.py
│ ├── megatron_weight_loaders.py
│ ├── model_loader.py
│ ├── model_runner.py
│ ├── parallel_state.py
│ ├── spmd_gpu_executor.py
│ ├── tokenizer.py
│ └── worker.py
├── trainer
├── __init__.py
├── config
│ ├── evaluation.yaml
│ ├── generation.yaml
│ ├── ppo_megatron_trainer.yaml
│ ├── ppo_trainer.yaml
│ └── sft_trainer.yaml
├── fsdp_sft_trainer.py
├── main_eval.py
├── main_generation.py
├── main_ppo.py
├── main_ppo_format.py
├── ppo
│ ├── __init__.py
│ ├── core_algos.py
│ └── ray_trainer.py
└── runtime_env.yaml
├── utils
├── __init__.py
├── config.py
├── dataset
│ ├── README.md
│ ├── __init__.py
│ ├── rl_dataset.py
│ └── rm_dataset.py
├── debug
│ ├── __init__.py
│ ├── performance.py
│ └── trajectory_tracker.py
├── distributed.py
├── flops_counter.py
├── fs.py
├── fsdp_utils.py
├── hdfs_io.py
├── import_utils.py
├── logger
│ ├── __init__.py
│ └── aggregate_logger.py
├── logging_utils.py
├── megatron
│ ├── __init__.py
│ ├── memory.py
│ ├── optimizer.py
│ ├── optimizer_config.py
│ ├── pipeline_parallel.py
│ ├── sequence_parallel.py
│ └── tensor_parallel.py
├── megatron_utils.py
├── memory_buffer.py
├── model.py
├── py_functional.py
├── ray_utils.py
├── rendezvous
│ ├── __init__.py
│ └── ray_backend.py
├── reward_score
│ ├── __init__.py
│ ├── countdown.py
│ ├── gsm8k.py
│ ├── math.py
│ ├── multiply.py
│ ├── qa_em.py
│ └── qa_em_format.py
├── seqlen_balancing.py
├── tokenizer.py
├── torch_dtypes.py
├── torch_functional.py
├── tracking.py
└── ulysses.py
├── version
└── version
└── workers
├── __init__.py
├── actor
├── __init__.py
├── base.py
├── dp_actor.py
└── megatron_actor.py
├── critic
├── __init__.py
├── base.py
├── dp_critic.py
└── megatron_critic.py
├── fsdp_workers.py
├── megatron_workers.py
├── reward_model
├── __init__.py
├── base.py
└── megatron
│ ├── __init__.py
│ └── reward_model.py
├── rollout
├── __init__.py
├── base.py
├── hf_rollout.py
├── naive
│ ├── __init__.py
│ └── naive_rollout.py
├── tokenizer.py
└── vllm_rollout
│ ├── __init__.py
│ └── vllm_rollout.py
└── sharding_manager
├── __init__.py
├── base.py
├── fsdp_ulysses.py
├── fsdp_vllm.py
└── megatron_vllm.py
/.gitignore:
--------------------------------------------------------------------------------
1 | **/*.pt
2 | **/checkpoints
3 | **/wget-log
4 | **/_build/
5 | **/*.ckpt
6 | **/outputs
7 | **/*.tar.gz
8 | **/playground
9 | **/wandb
10 |
11 | # Byte-compiled / optimized / DLL files
12 | __pycache__/
13 | *.py[cod]
14 | *$py.class
15 | dataset/*
16 | tensorflow/my_graph/*
17 | .idea/
18 | # C extensions
19 | *.so
20 | data
21 | sft/output/*
22 | sft/data/*
23 |
24 | # Distribution / packaging
25 | .Python
26 | build/
27 | develop-eggs/
28 | dist/
29 | downloads/
30 | eggs/
31 | .eggs/
32 | lib/
33 | lib64/
34 | parts/
35 | sdist/
36 | var/
37 | *.egg-info/
38 | .installed.cfg
39 | *.egg
40 |
41 | # PyInstaller
42 | # Usually these files are written by a python script from a template
43 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
44 | *.manifest
45 | *.spec
46 |
47 | # Installer logs
48 | pip-log.txt
49 | pip-delete-this-directory.txt
50 |
51 | # Unit test / coverage reports
52 | htmlcov/
53 | .tox/
54 | .coverage
55 | .coverage.*
56 | .cache
57 | nosetests.xml
58 | coverage.xml
59 | *,cover
60 | .hypothesis/
61 |
62 | # Translations
63 | *.mo
64 | *.pot
65 |
66 | # Django stuff:
67 | *.log
68 | local_settings.py
69 |
70 | image_outputs
71 |
72 | checkpoints
73 |
74 | # Flask stuff:
75 | instance/
76 | .webassets-cache
77 |
78 | # Scrapy stuff:
79 | .scrapy
80 |
81 | # Sphinx documentation
82 | docs/_build/
83 |
84 | # PyBuilder
85 | target/
86 |
87 | # IPython Notebook
88 | .ipynb_checkpoints
89 |
90 | # pyenv
91 | .python-version
92 |
93 | # celery beat schedule file
94 | celerybeat-schedule
95 |
96 |
97 | # virtualenv
98 | venv/
99 | ENV/
100 |
101 | # Spyder project settings
102 | .spyderproject
103 |
104 | # Rope project settings
105 | .ropeproject
106 |
107 | # vscode
108 | .vscode
109 |
110 | # Mac
111 | .DS_Store
112 |
113 | # output logs
114 | tests/e2e/toy_examples/deepspeed/synchronous/output.txt
115 |
116 | # vim
117 | *.swp
118 |
119 | # log*
120 | log/
121 |
122 | **logs
--------------------------------------------------------------------------------
/Notice.txt:
--------------------------------------------------------------------------------
1 | Copyright 2023-2024 Bytedance Ltd. and/or its affiliates
--------------------------------------------------------------------------------
/docs/experiment_log.md:
--------------------------------------------------------------------------------
1 |
2 | ## Experiment log
3 |
4 | ### Preliminary results
5 |
6 | Resources: [wandb](https://wandb.ai/peterjin/Search-R1-open)
7 |
8 |
9 | The preliminary experiment is conducted only on natural question (NQ) dataset (+ PPO) with a small number of training steps.
10 |
11 |
12 | ### v0.1
13 |
14 | Resources: [wandb](https://wandb.ai/peterjin/Search-R1-nq_hotpotqa_train), [docs](https://github.com/PeterGriffinJin/Search-R1/tree/main/scripts/nq_hotpotqa), [scripts](https://github.com/PeterGriffinJin/Search-R1/tree/main/scripts/nq_hotpotqa/v0.1)
15 |
16 |
17 | We extend the experiments from NQ to seven datasets with both PPO and GRPO methods. The studies are still on a small number of training steps with a big learning rate warm up ratio.
18 |
19 |
20 | ### v0.2
21 |
22 | Resources: [wandb](https://wandb.ai/peterjin/Search-R1-v0.2), [docs](https://github.com/PeterGriffinJin/Search-R1/tree/main/scripts/nq_hotpotqa), [scripts](https://github.com/PeterGriffinJin/Search-R1/tree/main/scripts/nq_hotpotqa/v0.2), [paper](https://arxiv.org/abs/2503.09516)
23 |
24 |
25 | We fix several bugs including [retrieved token masking](https://github.com/PeterGriffinJin/Search-R1/pull/21) and [GRPO sample indexing](https://github.com/PeterGriffinJin/Search-R1/commit/9ec2fa9892fbf0315d0c67b4dc08ae8f6cf5f378).
26 | The former can largely improve the stablity of RL training.
27 | Then we adjust the training scripts, increasing the number of training steps and decreasing the learning rate warm up ratio, to obtain a better performance, and conduct experiments on different scale of LLMs (3B, 7B, 14B).
28 |
29 |
30 | ### v0.3
31 |
32 | Resources: [wandb](https://wandb.ai/peterjin/Search-R1-v0.3), [docs](https://github.com/PeterGriffinJin/Search-R1/tree/main/scripts/nq_hotpotqa), [scripts](https://github.com/PeterGriffinJin/Search-R1/tree/main/scripts/nq_hotpotqa/v0.3), [paper](https://arxiv.org/abs/2505.15117)
33 |
34 | We conduct studies on (1) reward design; (2) LLM backbone; and (3) search engine.
35 |
36 | - Reward design
37 | - Format reward
38 | - Intermediate retrieval reward
39 | - LLM backbone
40 | - LLM type (e.g., general LLM or reasoning LLM)
41 | - LLM scale (3B/7B/14B/32B)
42 | - Search engine
43 | - RL training dynamics
44 | - generalization during inference
45 | - Data scaling
46 |
47 | Details can be found in the [paper](https://arxiv.org/abs/2505.15117).
48 |
--------------------------------------------------------------------------------
/example/multinode/train_grpo_multinode_32b.sh:
--------------------------------------------------------------------------------
1 | data_name=nq_hotpotqa_train
2 |
3 | export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
4 | export DATA_DIR=data/${data_name} # first download the data from https://huggingface.co/datasets/PeterJinGo/nq_hotpotqa_train
5 |
6 | WAND_PROJECT="Search-R1"
7 | RAY_DASHBOARD_ADDRESS="http://xx.xx.xx.xx:8265" # your head node address
8 | N_NODES=4
9 |
10 | export BASE_MODEL='Qwen/Qwen2.5-32B'
11 | export EXPERIMENT_NAME=${train_data}-${test_data}-search-r1-grpo-qwen2.5-32b-em-multinode-${N_NODES}
12 |
13 | # set -x
14 | export VLLM_ATTENTION_BACKEND=XFORMERS # vllm + qwen2-7b with flash_attn has some issues
15 |
16 | # max_prompt_length = (config['training']['max_start_length'] + config['training']['max_response_length'] * (config['training']['max_turns'] - 1) + config['training']['max_obs_length'] * config['training']['max_turns'])
17 |
18 | ulimit -n 65535
19 |
20 | ray job submit --address=$RAY_DASHBOARD_ADDRESS \
21 | --runtime-env=verl/trainer/runtime_env.yaml \
22 | --no-wait \
23 | -- \
24 | python3 -m verl.trainer.main_ppo \
25 | data.train_files=$DATA_DIR/train.parquet \
26 | data.val_files=$DATA_DIR/test.parquet \
27 | data.train_data_num=null \
28 | data.val_data_num=null \
29 | data.train_batch_size=512 \
30 | data.val_batch_size=256 \
31 | data.max_prompt_length=4096 \
32 | data.max_response_length=500 \
33 | data.max_start_length=2048 \
34 | data.max_obs_length=500 \
35 | data.shuffle_train_dataloader=True \
36 | algorithm.adv_estimator=grpo \
37 | actor_rollout_ref.model.path=$BASE_MODEL \
38 | actor_rollout_ref.model.enable_gradient_checkpointing=True \
39 | actor_rollout_ref.model.use_remove_padding=True \
40 | actor_rollout_ref.actor.optim.lr=2e-7 \
41 | actor_rollout_ref.actor.optim.lr_warmup_steps_ratio=0.285 \
42 | actor_rollout_ref.actor.use_kl_loss=True \
43 | actor_rollout_ref.actor.ppo_mini_batch_size=256 \
44 | actor_rollout_ref.actor.ppo_micro_batch_size=64 \
45 | actor_rollout_ref.actor.fsdp_config.param_offload=false \
46 | actor_rollout_ref.actor.fsdp_config.grad_offload=false \
47 | actor_rollout_ref.actor.fsdp_config.optimizer_offload=false \
48 | actor_rollout_ref.rollout.log_prob_micro_batch_size=128 \
49 | actor_rollout_ref.rollout.tensor_model_parallel_size=2 \
50 | actor_rollout_ref.rollout.name=vllm \
51 | actor_rollout_ref.rollout.gpu_memory_utilization=0.5 \
52 | actor_rollout_ref.ref.log_prob_micro_batch_size=128 \
53 | actor_rollout_ref.ref.fsdp_config.param_offload=false \
54 | actor_rollout_ref.actor.kl_loss_coef=0.001 \
55 | actor_rollout_ref.actor.kl_loss_type=low_var_kl \
56 | algorithm.no_think_rl=false \
57 | actor_rollout_ref.rollout.n_agent=5 \
58 | actor_rollout_ref.rollout.temperature=1 \
59 | actor_rollout_ref.actor.state_masking=True \
60 | trainer.logger=['wandb'] \
61 | +trainer.val_only=false \
62 | +trainer.val_before_train=false \
63 | trainer.default_hdfs_dir=null \
64 | trainer.n_gpus_per_node=8 \
65 | trainer.nnodes=$N_NODES \
66 | trainer.save_freq=100 \
67 | trainer.test_freq=100 \
68 | trainer.project_name=$WAND_PROJECT \
69 | trainer.experiment_name=$EXPERIMENT_NAME \
70 | trainer.total_epochs=15 \
71 | trainer.total_training_steps=1005 \
72 | trainer.default_hdfs_dir=null \
73 | trainer.default_local_dir=verl_checkpoints/$EXPERIMENT_NAME \
74 | max_turns=4 \
75 | retriever.url="http://127.0.0.1:8000/retrieve" \
76 | retriever.topk=3 \
77 | 2>&1 | tee $EXPERIMENT_NAME.log
78 |
--------------------------------------------------------------------------------
/example/multinode/train_grpo_multinode_72b.sh:
--------------------------------------------------------------------------------
1 | data_name=nq_hotpotqa_train
2 |
3 | export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
4 | export DATA_DIR=data/${data_name} # first download the data from https://huggingface.co/datasets/PeterJinGo/nq_hotpotqa_train
5 |
6 | WAND_PROJECT="Search-R1"
7 | RAY_DASHBOARD_ADDRESS="http://xx.xx.xx.xx:8265" # your head node address
8 | N_NODES=4
9 |
10 | export BASE_MODEL='Qwen/Qwen2.5-72B'
11 | export EXPERIMENT_NAME=${train_data}-${test_data}-search-r1-grpo-qwen2.5-72b-em-multinode-${N_NODES}
12 |
13 | # set -x
14 | export VLLM_ATTENTION_BACKEND=XFORMERS # vllm + qwen2-7b with flash_attn has some issues
15 |
16 | ulimit -n 65535
17 |
18 | ray job submit --address=$RAY_DASHBOARD_ADDRESS \
19 | --runtime-env=verl/trainer/runtime_env.yaml \
20 | --no-wait \
21 | -- \
22 | python3 -m verl.trainer.main_ppo \
23 | data.train_files=$DATA_DIR/train.parquet \
24 | data.val_files=$DATA_DIR/test.parquet \
25 | data.train_data_num=null \
26 | data.val_data_num=null \
27 | data.train_batch_size=512 \
28 | data.val_batch_size=256 \
29 | data.max_prompt_length=4096 \
30 | data.max_response_length=500 \
31 | data.max_start_length=2048 \
32 | data.max_obs_length=500 \
33 | data.shuffle_train_dataloader=True \
34 | algorithm.adv_estimator=grpo \
35 | actor_rollout_ref.model.path=$BASE_MODEL \
36 | actor_rollout_ref.model.enable_gradient_checkpointing=True \
37 | actor_rollout_ref.model.use_remove_padding=True \
38 | actor_rollout_ref.actor.optim.lr=1e-7 \
39 | actor_rollout_ref.actor.optim.lr_warmup_steps_ratio=0.285 \
40 | actor_rollout_ref.actor.use_kl_loss=True \
41 | actor_rollout_ref.actor.ppo_mini_batch_size=256 \
42 | actor_rollout_ref.actor.ppo_micro_batch_size=32 \
43 | actor_rollout_ref.actor.fsdp_config.param_offload=True \
44 | actor_rollout_ref.actor.fsdp_config.grad_offload=True \
45 | actor_rollout_ref.actor.fsdp_config.optimizer_offload=True \
46 | actor_rollout_ref.rollout.log_prob_micro_batch_size=32 \
47 | actor_rollout_ref.rollout.tensor_model_parallel_size=4 \
48 | actor_rollout_ref.rollout.name=vllm \
49 | actor_rollout_ref.rollout.gpu_memory_utilization=0.5 \
50 | actor_rollout_ref.ref.log_prob_micro_batch_size=32 \
51 | actor_rollout_ref.ref.fsdp_config.param_offload=True \
52 | actor_rollout_ref.actor.kl_loss_coef=0.001 \
53 | actor_rollout_ref.actor.kl_loss_type=low_var_kl \
54 | algorithm.no_think_rl=false \
55 | actor_rollout_ref.rollout.n_agent=5 \
56 | actor_rollout_ref.rollout.temperature=1 \
57 | actor_rollout_ref.actor.state_masking=True \
58 | trainer.logger=['wandb'] \
59 | +trainer.val_only=false \
60 | +trainer.val_before_train=false \
61 | trainer.default_hdfs_dir=null \
62 | trainer.n_gpus_per_node=8 \
63 | trainer.nnodes=$N_NODES \
64 | trainer.save_freq=100 \
65 | trainer.test_freq=100 \
66 | trainer.project_name=$WAND_PROJECT \
67 | trainer.experiment_name=$EXPERIMENT_NAME \
68 | trainer.total_epochs=15 \
69 | trainer.total_training_steps=1005 \
70 | trainer.default_hdfs_dir=null \
71 | trainer.default_local_dir=verl_checkpoints/$EXPERIMENT_NAME \
72 | max_turns=4 \
73 | retriever.url="http://127.0.0.1:8000/retrieve" \
74 | retriever.topk=3 \
75 | 2>&1 | tee $EXPERIMENT_NAME.log
76 |
--------------------------------------------------------------------------------
/example/multinode/train_ppo_multinode_32b.sh:
--------------------------------------------------------------------------------
1 | data_name=nq_hotpotqa_train
2 |
3 | export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
4 | export DATA_DIR=data/${data_name} # first download the data from https://huggingface.co/datasets/PeterJinGo/nq_hotpotqa_train
5 |
6 | WAND_PROJECT="Search-R1"
7 | RAY_DASHBOARD_ADDRESS="http://xx.xx.xx.xx:8265" # your head node address
8 | N_NODES=4
9 |
10 | export BASE_MODEL='Qwen/Qwen2.5-32B'
11 | export EXPERIMENT_NAME=${train_data}-${test_data}-search-r1-ppo-qwen2.5-32b-em-multinode-${N_NODES}
12 |
13 | # set -x
14 | export VLLM_ATTENTION_BACKEND=XFORMERS
15 |
16 | ulimit -n 65535
17 |
18 | ray job submit --address=$RAY_DASHBOARD_ADDRESS \
19 | --runtime-env=verl/trainer/runtime_env.yaml \
20 | --no-wait \
21 | -- \
22 | python3 -m verl.trainer.main_ppo \
23 | data.train_files=$DATA_DIR/train.parquet \
24 | data.val_files=$DATA_DIR/test.parquet \
25 | data.train_data_num=null \
26 | data.val_data_num=null \
27 | data.train_batch_size=512 \
28 | data.val_batch_size=256 \
29 | data.max_prompt_length=4096 \
30 | data.max_response_length=500 \
31 | data.max_start_length=2048 \
32 | data.max_obs_length=500 \
33 | data.shuffle_train_dataloader=True \
34 | algorithm.adv_estimator=gae \
35 | actor_rollout_ref.model.path=$BASE_MODEL \
36 | actor_rollout_ref.actor.optim.lr=2e-7 \
37 | actor_rollout_ref.model.enable_gradient_checkpointing=true \
38 | actor_rollout_ref.model.use_remove_padding=True \
39 | actor_rollout_ref.actor.optim.lr_warmup_steps_ratio=0.285 \
40 | actor_rollout_ref.actor.ppo_mini_batch_size=256 \
41 | actor_rollout_ref.actor.ppo_micro_batch_size=32 \
42 | actor_rollout_ref.actor.fsdp_config.param_offload=False \
43 | actor_rollout_ref.actor.fsdp_config.grad_offload=False \
44 | actor_rollout_ref.actor.fsdp_config.optimizer_offload=True \
45 | actor_rollout_ref.rollout.log_prob_micro_batch_size=32 \
46 | actor_rollout_ref.rollout.tensor_model_parallel_size=2 \
47 | actor_rollout_ref.rollout.name=vllm \
48 | actor_rollout_ref.rollout.gpu_memory_utilization=0.5 \
49 | actor_rollout_ref.ref.log_prob_micro_batch_size=32 \
50 | actor_rollout_ref.ref.fsdp_config.param_offload=False \
51 | actor_rollout_ref.rollout.n_agent=1 \
52 | actor_rollout_ref.rollout.temperature=1 \
53 | actor_rollout_ref.rollout.top_p=1.0 \
54 | actor_rollout_ref.actor.state_masking=true \
55 | critic.optim.lr=1e-5 \
56 | critic.model.use_remove_padding=True \
57 | critic.optim.lr_warmup_steps_ratio=0.015 \
58 | critic.model.path=$BASE_MODEL \
59 | critic.model.enable_gradient_checkpointing=true \
60 | critic.ppo_micro_batch_size=32 \
61 | critic.model.fsdp_config.param_offload=False \
62 | critic.model.fsdp_config.grad_offload=False \
63 | critic.model.fsdp_config.optimizer_offload=True \
64 | algorithm.kl_ctrl.kl_coef=0.001 \
65 | algorithm.no_think_rl=false \
66 | trainer.critic_warmup=0 \
67 | trainer.logger=['wandb'] \
68 | +trainer.val_only=false \
69 | +trainer.val_before_train=true \
70 | trainer.default_hdfs_dir=null \
71 | trainer.n_gpus_per_node=8 \
72 | trainer.nnodes=$N_NODES \
73 | trainer.save_freq=100 \
74 | trainer.test_freq=100 \
75 | trainer.project_name=$WAND_PROJECT \
76 | trainer.experiment_name=$EXPERIMENT_NAME \
77 | trainer.total_epochs=15 \
78 | trainer.total_training_steps=1005 \
79 | trainer.default_hdfs_dir=null \
80 | trainer.default_local_dir=verl_checkpoints/$EXPERIMENT_NAME \
81 | max_turns=4 \
82 | retriever.url="http://127.0.0.1:8000/retrieve" \
83 | retriever.topk=3 \
84 | 2>&1 | tee $EXPERIMENT_NAME.log
85 |
--------------------------------------------------------------------------------
/example/retriever/retrieval_launch_ann.sh:
--------------------------------------------------------------------------------
1 |
2 | file_path=/the/path/you/save/corpus
3 | index_file=$file_path/e5_HNSW64.index
4 | corpus_file=$file_path/wiki-18.jsonl
5 | retriever_name=e5
6 | retriever_path=intfloat/e5-base-v2
7 |
8 | python search_r1/search/retrieval_server.py --index_path $index_file \
9 | --corpus_path $corpus_file \
10 | --topk 3 \
11 | --retriever_name $retriever_name \
12 | --retriever_model $retriever_path
13 |
--------------------------------------------------------------------------------
/example/retriever/retrieval_launch_bm25.sh:
--------------------------------------------------------------------------------
1 |
2 | file_path=/the/path/you/save/corpus
3 | index_file=$file_path/bm25
4 | corpus_file=$file_path/wiki-18.jsonl
5 | retriever_name=bm25
6 |
7 | python search_r1/search/retrieval_server.py --index_path $index_file \
8 | --corpus_path $corpus_file \
9 | --topk 3 \
10 | --retriever_name $retriever_name
11 |
--------------------------------------------------------------------------------
/example/retriever/retrieval_launch_google.sh:
--------------------------------------------------------------------------------
1 |
2 | api_key="" # put your google custom API key here (https://developers.google.com/custom-search/v1/overview)
3 | cse_id="" # put your google cse API key here (https://developers.google.com/custom-search/v1/overview)
4 |
5 | python search_r1/search/internal_google_server.py --api_key $api_key \
6 | --topk 5 \
7 | --cse_id $cse_id \
8 | --snippet_only
9 |
--------------------------------------------------------------------------------
/example/retriever/retrieval_launch_hierarchical.sh:
--------------------------------------------------------------------------------
1 |
2 | file_path=/the/path/you/save/corpus
3 | index_file=$file_path/e5_Flat.index
4 | corpus_file=$file_path/wiki-18.jsonl
5 | retriever_name=e5
6 | retriever_path=intfloat/e5-base-v2
7 | reranker_path=cross-encoder/ms-marco-MiniLM-L12-v2
8 |
9 | python search_r1/search/retrieval_rerank_server.py --index_path $index_file \
10 | --corpus_path $corpus_file \
11 | --retrieval_topk 10 \
12 | --retriever_name $retriever_name \
13 | --retriever_model $retriever_path \
14 | --faiss_gpu \
15 | --reranking_topk 3 \
16 | --reranker_model $reranker_path \
17 | --reranker_batch_size 32
18 |
--------------------------------------------------------------------------------
/example/retriever/retrieval_launch_serpapi.sh:
--------------------------------------------------------------------------------
1 |
2 | search_url=https://serpapi.com/search
3 | serp_api_key="" # put your serp api key here (https://serpapi.com/)
4 |
5 | python search_r1/search/online_search_server.py --search_url $search_url \
6 | --topk 3 \
7 | --serp_api_key $serp_api_key
8 |
--------------------------------------------------------------------------------
/public/head.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PeterGriffinJin/Search-R1/67fcca7fb311a9ee0f5f32c98bc2b24cefc094da/public/head.png
--------------------------------------------------------------------------------
/public/llama32-3b.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PeterGriffinJin/Search-R1/67fcca7fb311a9ee0f5f32c98bc2b24cefc094da/public/llama32-3b.png
--------------------------------------------------------------------------------
/public/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PeterGriffinJin/Search-R1/67fcca7fb311a9ee0f5f32c98bc2b24cefc094da/public/logo.png
--------------------------------------------------------------------------------
/public/main.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PeterGriffinJin/Search-R1/67fcca7fb311a9ee0f5f32c98bc2b24cefc094da/public/main.png
--------------------------------------------------------------------------------
/public/multi-turn.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PeterGriffinJin/Search-R1/67fcca7fb311a9ee0f5f32c98bc2b24cefc094da/public/multi-turn.png
--------------------------------------------------------------------------------
/public/single-turn.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PeterGriffinJin/Search-R1/67fcca7fb311a9ee0f5f32c98bc2b24cefc094da/public/single-turn.png
--------------------------------------------------------------------------------
/public/status.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PeterGriffinJin/Search-R1/67fcca7fb311a9ee0f5f32c98bc2b24cefc094da/public/status.png
--------------------------------------------------------------------------------
/public/worker.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PeterGriffinJin/Search-R1/67fcca7fb311a9ee0f5f32c98bc2b24cefc094da/public/worker.png
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | # -------------------------------
2 | # build-system
3 | # -------------------------------
4 | [build-system]
5 | requires = [
6 | "setuptools>=61.0",
7 | "wheel"
8 | ]
9 | build-backend = "setuptools.build_meta"
10 |
11 | # -------------------------------
12 | # project (PEP 621 metadata)
13 | # -------------------------------
14 | [project]
15 | name = "verl"
16 | # We'll mark the version as "dynamic" because it's read from the file "verl/version/version"
17 | # (PEP 621 calls this "dynamic version").
18 | # The actual version is specified in the [tool.setuptools.dynamic] section below.
19 | dynamic = ["version"]
20 |
21 | description = "veRL: Volcano Engine Reinforcement Learning for LLM"
22 | license = {file = "LICENSE"} # or "Apache-2.0", if you prefer an SPDX identifier
23 | readme = {file = "README.md", content-type = "text/markdown"}
24 | requires-python = ">=3.8"
25 |
26 | authors = [
27 | { name = "Bytedance - Seed - MLSys", email = "zhangchi.usc1992@bytedance.com" },
28 | { name = "Bytedance - Seed - MLSys", email = "gmsheng@connect.hku.hk" },
29 | ]
30 |
31 | # Dependencies corresponding to install_requires in setup.py
32 | dependencies = [
33 | "accelerate",
34 | "codetiming",
35 | "datasets",
36 | "dill",
37 | "hydra-core",
38 | "numpy",
39 | "pybind11",
40 | "ray",
41 | "tensordict",
42 | "transformers<4.48",
43 | "vllm<=0.6.3",
44 | ]
45 |
46 | # Optional dependencies (extras_require in setup.py)
47 | [project.optional-dependencies]
48 | test = [
49 | "pytest", "yapf"
50 | ]
51 |
52 | # URLs
53 | [project.urls]
54 | Homepage = "https://github.com/volcengine/verl"
55 |
56 | # -------------------------------
57 | # tool.setuptools - Additional config
58 | # -------------------------------
59 | [tool.setuptools]
60 | # True means `setuptools` will attempt to include all relevant files in package_data automatically.
61 | # This corresponds to `include_package_data=True` in setup.py.
62 | include-package-data = true
63 |
64 | # We read the version from a file in 'verl/version/version'
65 | [tool.setuptools.dynamic]
66 | version = {file = "verl/version/version"}
67 |
68 | # If you need to mimic `package_dir={'': '.'}`:
69 | [tool.setuptools.package-dir]
70 | "" = "."
71 |
72 | # If you need to include specific non-Python data (like YAML files or version file):
73 | # This is the rough equivalent of package_data={'': ['version/*'], 'verl': ['trainer/config/*.yaml']}
74 | [tool.setuptools.package-data]
75 | verl = [
76 | "version/*",
77 | "trainer/config/*.yaml"
78 | ]
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | accelerate
2 | codetiming
3 | datasets
4 | dill
5 | flash-attn
6 | hydra-core
7 | numpy
8 | pandas
9 | pybind11
10 | ray
11 | tensordict<0.6
12 | transformers<4.48
13 | vllm<=0.6.3
14 | wandb
15 | IPython
16 | matplotlib
--------------------------------------------------------------------------------
/retrieval_launch.sh:
--------------------------------------------------------------------------------
1 |
2 | file_path=/the/path/you/save/corpus
3 | index_file=$file_path/e5_Flat.index
4 | corpus_file=$file_path/wiki-18.jsonl
5 | retriever_name=e5
6 | retriever_path=intfloat/e5-base-v2
7 |
8 | python search_r1/search/retrieval_server.py --index_path $index_file \
9 | --corpus_path $corpus_file \
10 | --topk 3 \
11 | --retriever_name $retriever_name \
12 | --retriever_model $retriever_path \
13 | --faiss_gpu
14 |
--------------------------------------------------------------------------------
/scripts/data_process/nq.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | Preprocess the nq dataset to parquet format
16 | """
17 |
18 | import re
19 | import os
20 | import datasets
21 |
22 | from verl.utils.hdfs_io import copy, makedirs
23 | import argparse
24 |
25 |
26 | def make_prefix(dp, template_type):
27 | question = dp['question']
28 |
29 | # NOTE: also need to change reward_score/countdown.py
30 | if template_type == 'base':
31 | """This works for any base model"""
32 | prefix = f"""Answer the given question. \
33 | You should first have a reasoning process in mind and then provides the answer. \
34 | Show your reasoning in tags and return the final answer in tags, for example Beijing . \
35 | Question: {question}\n"""
36 | else:
37 | raise NotImplementedError
38 | return prefix
39 |
40 |
41 | if __name__ == '__main__':
42 | parser = argparse.ArgumentParser()
43 | parser.add_argument('--local_dir', default='./data/nq')
44 | parser.add_argument('--hdfs_dir', default=None)
45 | parser.add_argument('--template_type', type=str, default='base')
46 |
47 | args = parser.parse_args()
48 |
49 | data_source = 'nq'
50 |
51 | dataset = datasets.load_dataset('RUC-NLPIR/FlashRAG_datasets', 'nq')
52 |
53 | train_dataset = dataset['train']
54 | test_dataset = dataset['test']
55 |
56 | # add a row to each data item that represents a unique id
57 | def make_map_fn(split):
58 |
59 | def process_fn(example, idx):
60 | example['question'] = example['question'].strip()
61 | if example['question'][-1] != '?':
62 | example['question'] += '?'
63 | question = make_prefix(example, template_type=args.template_type)
64 | solution = {
65 | "target": example['golden_answers'],
66 | }
67 |
68 | data = {
69 | "data_source": data_source,
70 | "prompt": [{
71 | "role": "user",
72 | "content": question,
73 | }],
74 | "ability": "fact-reasoning",
75 | "reward_model": {
76 | "style": "rule",
77 | "ground_truth": solution
78 | },
79 | "extra_info": {
80 | 'split': split,
81 | 'index': idx,
82 | }
83 | }
84 | return data
85 |
86 | return process_fn
87 |
88 | train_dataset = train_dataset.map(function=make_map_fn('train'), with_indices=True)
89 | test_dataset = test_dataset.map(function=make_map_fn('test'), with_indices=True)
90 |
91 | local_dir = args.local_dir
92 | hdfs_dir = args.hdfs_dir
93 |
94 | train_dataset.to_parquet(os.path.join(local_dir, 'train.parquet'))
95 | test_dataset.to_parquet(os.path.join(local_dir, 'test.parquet'))
96 |
97 | if hdfs_dir is not None:
98 | makedirs(hdfs_dir)
99 |
100 | copy(src=local_dir, dst=hdfs_dir)
101 |
--------------------------------------------------------------------------------
/scripts/data_process/nq_search.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | Preprocess the nq dataset to parquet format
16 | """
17 |
18 | import re
19 | import os
20 | import datasets
21 |
22 | from verl.utils.hdfs_io import copy, makedirs
23 | import argparse
24 |
25 |
26 | def make_prefix(dp, template_type):
27 | question = dp['question']
28 |
29 | # NOTE: also need to change reward_score/countdown.py
30 | if template_type == 'base':
31 | """This works for any base model"""
32 | prefix = f"""Answer the given question. \
33 | You must conduct reasoning inside and first every time you get new information. \
34 | After reasoning, if you find you lack some knowledge, you can call a search engine by query and it will return the top searched results between and . \
35 | You can search as many times as your want. \
36 | If you find no further external knowledge needed, you can directly provide the answer inside and , without detailed illustrations. For example, Beijing . Question: {question}\n"""
37 | else:
38 | raise NotImplementedError
39 | return prefix
40 |
41 |
42 | if __name__ == '__main__':
43 | parser = argparse.ArgumentParser()
44 | parser.add_argument('--local_dir', default='./data/nq_search')
45 | parser.add_argument('--hdfs_dir', default=None)
46 | parser.add_argument('--template_type', type=str, default='base')
47 |
48 | args = parser.parse_args()
49 |
50 | data_source = 'nq'
51 |
52 | dataset = datasets.load_dataset('RUC-NLPIR/FlashRAG_datasets', 'nq')
53 |
54 | train_dataset = dataset['train']
55 | test_dataset = dataset['test']
56 |
57 | # add a row to each data item that represents a unique id
58 | def make_map_fn(split):
59 |
60 | def process_fn(example, idx):
61 | example['question'] = example['question'].strip()
62 | if example['question'][-1] != '?':
63 | example['question'] += '?'
64 | question = make_prefix(example, template_type=args.template_type)
65 | solution = {
66 | "target": example['golden_answers'],
67 | }
68 |
69 | data = {
70 | "data_source": data_source,
71 | "prompt": [{
72 | "role": "user",
73 | "content": question,
74 | }],
75 | "ability": "fact-reasoning",
76 | "reward_model": {
77 | "style": "rule",
78 | "ground_truth": solution
79 | },
80 | "extra_info": {
81 | 'split': split,
82 | 'index': idx,
83 | }
84 | }
85 | return data
86 |
87 | return process_fn
88 |
89 | train_dataset = train_dataset.map(function=make_map_fn('train'), with_indices=True)
90 | test_dataset = test_dataset.map(function=make_map_fn('test'), with_indices=True)
91 |
92 | local_dir = args.local_dir
93 | hdfs_dir = args.hdfs_dir
94 |
95 | train_dataset.to_parquet(os.path.join(local_dir, 'train.parquet'))
96 | test_dataset.to_parquet(os.path.join(local_dir, 'test.parquet'))
97 |
98 | if hdfs_dir is not None:
99 | makedirs(hdfs_dir)
100 |
101 | copy(src=local_dir, dst=hdfs_dir)
102 |
--------------------------------------------------------------------------------
/scripts/data_process/qa_search_train_merge.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | Preprocess the QA dataset to parquet format
16 | """
17 |
18 | import re
19 | import os
20 | import datasets
21 |
22 | from verl.utils.hdfs_io import copy, makedirs
23 | import argparse
24 |
25 |
26 | def make_prefix(dp, template_type):
27 | question = dp['question']
28 |
29 | # NOTE: also need to change reward_score/countdown.py
30 | if template_type == 'base':
31 | """This works for any base model"""
32 | prefix = f"""Answer the given question. \
33 | You must conduct reasoning inside and first every time you get new information. \
34 | After reasoning, if you find you lack some knowledge, you can call a search engine by query and it will return the top searched results between and . \
35 | You can search as many times as your want. \
36 | If you find no further external knowledge needed, you can directly provide the answer inside and , without detailed illustrations. For example, Beijing . Question: {question}\n"""
37 | else:
38 | raise NotImplementedError
39 | return prefix
40 |
41 |
42 | if __name__ == '__main__':
43 | parser = argparse.ArgumentParser()
44 | parser.add_argument('--local_dir', default='./data/nq_search')
45 | parser.add_argument('--hdfs_dir', default=None)
46 | parser.add_argument('--template_type', type=str, default='base')
47 | parser.add_argument('--data_sources', default='nq')
48 |
49 | args = parser.parse_args()
50 |
51 | # data_source = 'nq'
52 | data_sources = args.data_sources.split(',')
53 | all_dataset = []
54 |
55 | for data_source in data_sources:
56 |
57 | dataset = datasets.load_dataset('RUC-NLPIR/FlashRAG_datasets', data_source)
58 |
59 | train_dataset = dataset['train']
60 |
61 | # add a row to each data item that represents a unique id
62 | def make_map_fn(split):
63 |
64 | def process_fn(example, idx):
65 | example['question'] = example['question'].strip()
66 | if example['question'][-1] != '?':
67 | example['question'] += '?'
68 | question = make_prefix(example, template_type=args.template_type)
69 | solution = {
70 | "target": example['golden_answers'],
71 | }
72 |
73 | data = {
74 | "data_source": data_source,
75 | "prompt": [{
76 | "role": "user",
77 | "content": question,
78 | }],
79 | "ability": "fact-reasoning",
80 | "reward_model": {
81 | "style": "rule",
82 | "ground_truth": solution
83 | },
84 | "extra_info": {
85 | 'split': split,
86 | 'index': idx,
87 | }
88 | }
89 | return data
90 |
91 | return process_fn
92 |
93 | train_dataset = train_dataset.map(function=make_map_fn('train'), with_indices=True)
94 | all_dataset.append(train_dataset)
95 |
96 | local_dir = args.local_dir
97 | hdfs_dir = args.hdfs_dir
98 |
99 | all_train_dataset = datasets.concatenate_datasets(all_dataset)
100 | all_train_dataset.to_parquet(os.path.join(local_dir, 'train.parquet'))
101 |
102 | if hdfs_dir is not None:
103 | makedirs(hdfs_dir)
104 |
105 | copy(src=local_dir, dst=hdfs_dir)
106 |
--------------------------------------------------------------------------------
/scripts/download.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | from huggingface_hub import hf_hub_download
3 |
4 | parser = argparse.ArgumentParser(description="Download files from a Hugging Face dataset repository.")
5 | parser.add_argument("--repo_id", type=str, default="PeterJinGo/wiki-18-e5-index", help="Hugging Face repository ID")
6 | parser.add_argument("--save_path", type=str, required=True, help="Local directory to save files")
7 |
8 | args = parser.parse_args()
9 |
10 | repo_id = "PeterJinGo/wiki-18-e5-index"
11 | for file in ["part_aa", "part_ab"]:
12 | hf_hub_download(
13 | repo_id=repo_id,
14 | filename=file, # e.g., "e5_Flat.index"
15 | repo_type="dataset",
16 | local_dir=args.save_path,
17 | )
18 |
19 | repo_id = "PeterJinGo/wiki-18-corpus"
20 | hf_hub_download(
21 | repo_id=repo_id,
22 | filename="wiki-18.jsonl.gz",
23 | repo_type="dataset",
24 | local_dir=args.save_path,
25 | )
26 |
--------------------------------------------------------------------------------
/scripts/download.sh:
--------------------------------------------------------------------------------
1 |
2 | save_path=/home/peterjin/debug_cache
3 |
4 | python download.py --savepath $savepath
5 |
6 | cat $save_path/part_* > e5_Flat.index
7 |
--------------------------------------------------------------------------------
/scripts/nq_hotpotqa/README.md:
--------------------------------------------------------------------------------
1 |
2 | ## Reproduce the paper results
3 |
4 | ### Download the dataset
5 |
6 | ```bash
7 | huggingface-cli download --repo-type dataset PeterJinGo/nq_hotpotqa_train --local-dir $WORK_DIR/data/nq_hotpotqa_train
8 | ```
9 |
10 | ### Run PPO training
11 | ```bash
12 | bash train_ppo.sh
13 | ```
14 |
15 |
16 | ### Run GRPO training
17 | ```bash
18 | bash train_ppo.sh
19 | ```
20 |
21 | ### Run evaluation
22 | ```bash
23 | bash evaluate.sh
24 | ```
25 |
26 | You can change ```$BASE_MODEL``` to the path of the model you would like to evaluate.
27 |
--------------------------------------------------------------------------------
/scripts/nq_hotpotqa/data_process.sh:
--------------------------------------------------------------------------------
1 | WORK_DIR=your/work/dir
2 | LOCAL_DIR=$WORK_DIR/data/nq_hotpotqa_train
3 |
4 | ## process multiple dataset search format train file
5 | DATA=nq,hotpotqa
6 | python $WORK_DIR/scripts/data_process/qa_search_train_merge.py --local_dir $LOCAL_DIR --data_sources $DATA
7 |
8 | ## process multiple dataset search format test file
9 | DATA=nq,triviaqa,popqa,hotpotqa,2wikimultihopqa,musique,bamboogle
10 | python $WORK_DIR/scripts/data_process/qa_search_test_merge.py --local_dir $LOCAL_DIR --data_sources $DATA
11 |
--------------------------------------------------------------------------------
/scripts/nq_hotpotqa/evaluate.sh:
--------------------------------------------------------------------------------
1 | data_name=nq_hotpotqa_train
2 |
3 | export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
4 | export DATA_DIR=data/${data_name} # first download the data from https://huggingface.co/datasets/PeterJinGo/nq_hotpotqa_train
5 |
6 | export BASE_MODEL=""
7 |
8 | # set -x
9 | export VLLM_ATTENTION_BACKEND=XFORMERS # vllm + qwen2-7b with flash_attn has some issues
10 |
11 | # max_prompt_length = (config['training']['max_start_length'] + config['training']['max_response_length'] * (config['training']['max_turns'] - 1) + config['training']['max_obs_length'] * config['training']['max_turns'])
12 |
13 | PYTHONUNBUFFERED=1 python3 -m verl.trainer.main_ppo \
14 | data.train_files=$DATA_DIR/train.parquet \
15 | data.val_files=$DATA_DIR/test.parquet \
16 | data.train_data_num=null \
17 | data.val_data_num=null \
18 | data.train_batch_size=512 \
19 | data.val_batch_size=256 \
20 | data.max_prompt_length=4096 \
21 | data.max_response_length=500 \
22 | data.max_start_length=2048 \
23 | data.max_obs_length=500 \
24 | data.shuffle_train_dataloader=True \
25 | algorithm.adv_estimator=gae \
26 | actor_rollout_ref.model.path=$BASE_MODEL \
27 | actor_rollout_ref.actor.optim.lr=1e-6 \
28 | actor_rollout_ref.model.enable_gradient_checkpointing=true \
29 | actor_rollout_ref.model.use_remove_padding=True \
30 | actor_rollout_ref.actor.optim.lr_warmup_steps_ratio=0.95 \
31 | actor_rollout_ref.actor.ppo_mini_batch_size=256 \
32 | actor_rollout_ref.actor.ppo_micro_batch_size=64 \
33 | actor_rollout_ref.actor.fsdp_config.param_offload=true \
34 | actor_rollout_ref.actor.fsdp_config.grad_offload=true \
35 | actor_rollout_ref.actor.fsdp_config.optimizer_offload=true \
36 | actor_rollout_ref.rollout.log_prob_micro_batch_size=128 \
37 | actor_rollout_ref.rollout.tensor_model_parallel_size=1 \
38 | actor_rollout_ref.rollout.name=vllm \
39 | actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
40 | actor_rollout_ref.ref.log_prob_micro_batch_size=128 \
41 | actor_rollout_ref.ref.fsdp_config.param_offload=True \
42 | actor_rollout_ref.rollout.n_agent=1 \
43 | actor_rollout_ref.rollout.temperature=1 \
44 | actor_rollout_ref.actor.state_masking=true \
45 | critic.optim.lr=1e-5 \
46 | critic.model.use_remove_padding=True \
47 | critic.optim.lr_warmup_steps_ratio=0.05 \
48 | critic.model.path=$BASE_MODEL \
49 | critic.model.enable_gradient_checkpointing=true \
50 | critic.ppo_micro_batch_size=8 \
51 | critic.model.fsdp_config.param_offload=true \
52 | critic.model.fsdp_config.grad_offload=true \
53 | critic.model.fsdp_config.optimizer_offload=true \
54 | algorithm.kl_ctrl.kl_coef=0.001 \
55 | algorithm.no_think_rl=false \
56 | trainer.critic_warmup=0 \
57 | trainer.logger=[] \
58 | +trainer.val_only=true \
59 | +trainer.val_before_train=true \
60 | trainer.default_hdfs_dir=null \
61 | trainer.n_gpus_per_node=8 \
62 | trainer.nnodes=1 \
63 | max_turns=4 \
64 | retriever.url="http://127.0.0.1:8000/retrieve" \
65 | retriever.topk=3
66 |
--------------------------------------------------------------------------------
/scripts/nq_hotpotqa/v0.1/train_grpo.sh:
--------------------------------------------------------------------------------
1 | data_name=nq_hotpotqa_train
2 |
3 | export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
4 | export DATA_DIR=data/${data_name} # first download the data from https://huggingface.co/datasets/PeterJinGo/nq_hotpotqa_train
5 |
6 | WAND_PROJECT="Search-R1"
7 |
8 | export BASE_MODEL='meta-llama/Llama-3.2-3B'
9 | export EXPERIMENT_NAME=${data_name}-search-r1-grpo-llama3.2-3b-em
10 | # export BASE_MODEL='meta-llama/Llama-3.2-3B-Instruct'
11 | # export EXPERIMENT_NAME=${data_name}-search-r1-grpo-llama3.2-3b-it-em
12 | # export BASE_MODEL='meta-llama/Llama-3.1-8B'
13 | # export EXPERIMENT_NAME=${data_name}-search-r1-grpo-llama3.1-8b-em
14 | # export BASE_MODEL='meta-llama/Llama-3.1-8B-Instruct'
15 | # export EXPERIMENT_NAME=${data_name}-search-r1-grpo-llama3.1-8b-it-em
16 |
17 | # export BASE_MODEL='Qwen/Qwen2.5-3B'
18 | # export EXPERIMENT_NAME=${data_name}-search-r1-grpo-qwen2.5-3b-em
19 | # export BASE_MODEL='Qwen/Qwen2.5-3B-Instruct'
20 | # export EXPERIMENT_NAME=${data_name}-search-r1-grpo-qwen2.5-3b-it-em
21 | # export BASE_MODEL='Qwen/Qwen2.5-7B'
22 | # export EXPERIMENT_NAME=${data_name}-search-r1-grpo-qwen2.5-7b-em
23 | # export BASE_MODEL='Qwen/Qwen2.5-7B-Instruct'
24 | # export EXPERIMENT_NAME=${data_name}-search-r1-grpo-qwen2.5-7b-it-em
25 |
26 | # set -x
27 | export VLLM_ATTENTION_BACKEND=XFORMERS # vllm + qwen2-7b with flash_attn has some issues
28 |
29 | # max_prompt_length = (config['training']['max_start_length'] + config['training']['max_response_length'] * (config['training']['max_turns'] - 1) + config['training']['max_obs_length'] * config['training']['max_turns'])
30 |
31 | PYTHONUNBUFFERED=1 python3 -m verl.trainer.main_ppo \
32 | data.train_files=$DATA_DIR/train.parquet \
33 | data.val_files=$DATA_DIR/test.parquet \
34 | data.train_data_num=null \
35 | data.val_data_num=null \
36 | data.train_batch_size=512 \
37 | data.val_batch_size=256 \
38 | data.max_prompt_length=4096 \
39 | data.max_response_length=500 \
40 | data.max_start_length=2048 \
41 | data.max_obs_length=500 \
42 | data.shuffle_train_dataloader=True \
43 | algorithm.adv_estimator=grpo \
44 | actor_rollout_ref.model.path=$BASE_MODEL \
45 | actor_rollout_ref.model.enable_gradient_checkpointing=true \
46 | actor_rollout_ref.model.use_remove_padding=True \
47 | actor_rollout_ref.actor.optim.lr=1e-6 \
48 | actor_rollout_ref.actor.optim.lr_warmup_steps_ratio=0.95 \
49 | actor_rollout_ref.actor.use_kl_loss=true \
50 | actor_rollout_ref.actor.ppo_mini_batch_size=256 \
51 | actor_rollout_ref.actor.ppo_micro_batch_size=64 \
52 | actor_rollout_ref.actor.fsdp_config.param_offload=true \
53 | actor_rollout_ref.actor.fsdp_config.grad_offload=true \
54 | actor_rollout_ref.actor.fsdp_config.optimizer_offload=true \
55 | actor_rollout_ref.rollout.log_prob_micro_batch_size=128 \
56 | actor_rollout_ref.rollout.tensor_model_parallel_size=1 \
57 | actor_rollout_ref.rollout.name=vllm \
58 | actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
59 | actor_rollout_ref.ref.log_prob_micro_batch_size=128 \
60 | actor_rollout_ref.ref.fsdp_config.param_offload=True \
61 | actor_rollout_ref.actor.kl_loss_coef=0.001 \
62 | actor_rollout_ref.actor.kl_loss_type=low_var_kl \
63 | algorithm.no_think_rl=false \
64 | actor_rollout_ref.rollout.n_agent=5 \
65 | actor_rollout_ref.rollout.temperature=1 \
66 | actor_rollout_ref.actor.state_masking=true \
67 | trainer.logger=['wandb'] \
68 | +trainer.val_only=false \
69 | +trainer.val_before_train=true \
70 | trainer.default_hdfs_dir=null \
71 | trainer.n_gpus_per_node=8 \
72 | trainer.nnodes=1 \
73 | trainer.save_freq=100 \
74 | trainer.test_freq=50 \
75 | trainer.project_name=$WAND_PROJECT \
76 | trainer.experiment_name=$EXPERIMENT_NAME \
77 | trainer.total_epochs=15 \
78 | trainer.total_training_steps=305 \
79 | trainer.default_hdfs_dir=null \
80 | trainer.default_local_dir=verl_checkpoints/$EXPERIMENT_NAME \
81 | max_turns=4 \
82 | retriever.url="http://127.0.0.1:8000/retrieve" \
83 | retriever.topk=3 \
84 | 2>&1 | tee $EXPERIMENT_NAME.log
85 |
--------------------------------------------------------------------------------
/scripts/nq_hotpotqa/v0.1/train_ppo.sh:
--------------------------------------------------------------------------------
1 | data_name=nq_hotpotqa_train
2 |
3 | export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
4 | export DATA_DIR=data/${data_name} # first download the data from https://huggingface.co/datasets/PeterJinGo/nq_hotpotqa_train
5 |
6 | WAND_PROJECT="Search-R1"
7 |
8 | export BASE_MODEL='meta-llama/Llama-3.2-3B'
9 | export EXPERIMENT_NAME=${data_name}-search-r1-ppo-llama3.2-3b-em
10 | # export BASE_MODEL='meta-llama/Llama-3.2-3B-Instruct'
11 | # export EXPERIMENT_NAME=${data_name}-search-r1-ppo-llama3.2-3b-it-em
12 | # export BASE_MODEL='meta-llama/Llama-3.1-8B'
13 | # export EXPERIMENT_NAME=${data_name}-search-r1-ppo-llama3.1-8b-em
14 | # export BASE_MODEL='meta-llama/Llama-3.1-8B-Instruct'
15 | # export EXPERIMENT_NAME=${data_name}-search-r1-ppo-llama3.1-8b-it-em
16 |
17 | # export BASE_MODEL='Qwen/Qwen2.5-3B'
18 | # export EXPERIMENT_NAME=${data_name}-search-r1-ppo-qwen2.5-3b-em
19 | # export BASE_MODEL='Qwen/Qwen2.5-3B-Instruct'
20 | # export EXPERIMENT_NAME=${data_name}-search-r1-ppo-qwen2.5-3b-it-em
21 | # export BASE_MODEL='Qwen/Qwen2.5-7B'
22 | # export EXPERIMENT_NAME=${data_name}-search-r1-ppo-qwen2.5-7b-em
23 | # export BASE_MODEL='Qwen/Qwen2.5-7B-Instruct'
24 | # export EXPERIMENT_NAME=${data_name}-search-r1-ppo-qwen2.5-7b-it-em
25 |
26 | # set -x
27 | export VLLM_ATTENTION_BACKEND=XFORMERS # vllm + qwen2-7b with flash_attn has some issues
28 |
29 | # max_prompt_length = (config['training']['max_start_length'] + config['training']['max_response_length'] * (config['training']['max_turns'] - 1) + config['training']['max_obs_length'] * config['training']['max_turns'])
30 |
31 | PYTHONUNBUFFERED=1 python3 -m verl.trainer.main_ppo \
32 | data.train_files=$DATA_DIR/train.parquet \
33 | data.val_files=$DATA_DIR/test.parquet \
34 | data.train_data_num=null \
35 | data.val_data_num=null \
36 | data.train_batch_size=512 \
37 | data.val_batch_size=256 \
38 | data.max_prompt_length=4096 \
39 | data.max_response_length=500 \
40 | data.max_start_length=2048 \
41 | data.max_obs_length=500 \
42 | data.shuffle_train_dataloader=True \
43 | algorithm.adv_estimator=gae \
44 | actor_rollout_ref.model.path=$BASE_MODEL \
45 | actor_rollout_ref.actor.optim.lr=1e-6 \
46 | actor_rollout_ref.model.enable_gradient_checkpointing=true \
47 | actor_rollout_ref.model.use_remove_padding=True \
48 | actor_rollout_ref.actor.optim.lr_warmup_steps_ratio=0.95 \
49 | actor_rollout_ref.actor.ppo_mini_batch_size=256 \
50 | actor_rollout_ref.actor.ppo_micro_batch_size=64 \
51 | actor_rollout_ref.actor.fsdp_config.param_offload=true \
52 | actor_rollout_ref.actor.fsdp_config.grad_offload=true \
53 | actor_rollout_ref.actor.fsdp_config.optimizer_offload=true \
54 | actor_rollout_ref.rollout.log_prob_micro_batch_size=128 \
55 | actor_rollout_ref.rollout.tensor_model_parallel_size=1 \
56 | actor_rollout_ref.rollout.name=vllm \
57 | actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
58 | actor_rollout_ref.ref.log_prob_micro_batch_size=128 \
59 | actor_rollout_ref.ref.fsdp_config.param_offload=True \
60 | actor_rollout_ref.rollout.n_agent=1 \
61 | actor_rollout_ref.rollout.temperature=1 \
62 | actor_rollout_ref.actor.state_masking=true \
63 | critic.optim.lr=1e-5 \
64 | critic.model.use_remove_padding=True \
65 | critic.optim.lr_warmup_steps_ratio=0.05 \
66 | critic.model.path=$BASE_MODEL \
67 | critic.model.enable_gradient_checkpointing=true \
68 | critic.ppo_micro_batch_size=8 \
69 | critic.model.fsdp_config.param_offload=true \
70 | critic.model.fsdp_config.grad_offload=true \
71 | critic.model.fsdp_config.optimizer_offload=true \
72 | algorithm.kl_ctrl.kl_coef=0.001 \
73 | algorithm.no_think_rl=false \
74 | trainer.critic_warmup=0 \
75 | trainer.logger=['wandb'] \
76 | +trainer.val_only=false \
77 | +trainer.val_before_train=true \
78 | trainer.default_hdfs_dir=null \
79 | trainer.n_gpus_per_node=8 \
80 | trainer.nnodes=1 \
81 | trainer.save_freq=100 \
82 | trainer.test_freq=50 \
83 | trainer.project_name=$WAND_PROJECT \
84 | trainer.experiment_name=$EXPERIMENT_NAME \
85 | trainer.total_epochs=15 \
86 | trainer.total_training_steps=305 \
87 | trainer.default_hdfs_dir=null \
88 | trainer.default_local_dir=verl_checkpoints/$EXPERIMENT_NAME \
89 | max_turns=4 \
90 | retriever.url="http://127.0.0.1:8000/retrieve" \
91 | retriever.topk=3 \
92 | 2>&1 | tee $EXPERIMENT_NAME.log
93 |
--------------------------------------------------------------------------------
/scripts/nq_hotpotqa/v0.2/train_grpo.sh:
--------------------------------------------------------------------------------
1 | data_name=nq_hotpotqa_train
2 |
3 | export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
4 | export DATA_DIR=data/${data_name} # first download the data from https://huggingface.co/datasets/PeterJinGo/nq_hotpotqa_train
5 |
6 | WAND_PROJECT="Search-R1"
7 |
8 | # export BASE_MODEL='Qwen/Qwen2.5-3B'
9 | # export EXPERIMENT_NAME=${train_data}-${test_data}-search-r1-grpo-qwen2.5-3b-em
10 | # export BASE_MODEL='Qwen/Qwen2.5-3B-Instruct'
11 | # export EXPERIMENT_NAME=${train_data}-${test_data}-search-r1-grpo-qwen2.5-3b-it-em
12 | export BASE_MODEL='Qwen/Qwen2.5-7B'
13 | export EXPERIMENT_NAME=${train_data}-${test_data}-search-r1-grpo-qwen2.5-7b-em
14 | # export BASE_MODEL='Qwen/Qwen2.5-7B-Instruct'
15 | # export EXPERIMENT_NAME=${train_data}-${test_data}-search-r1-grpo-qwen2.5-7b-it-em
16 | # export BASE_MODEL='Qwen/Qwen2.5-14B'
17 | # export EXPERIMENT_NAME=${train_data}-${test_data}-search-r1-grpo-qwen2.5-14b-em
18 | # export BASE_MODEL='Qwen/Qwen2.5-14B-Instruct'
19 | # export EXPERIMENT_NAME=${train_data}-${test_data}-search-r1-grpo-qwen2.5-14b-it-em
20 |
21 | # set -x
22 | export VLLM_ATTENTION_BACKEND=XFORMERS # vllm + qwen2-7b with flash_attn has some issues
23 |
24 | # max_prompt_length = (config['training']['max_start_length'] + config['training']['max_response_length'] * (config['training']['max_turns'] - 1) + config['training']['max_obs_length'] * config['training']['max_turns'])
25 |
26 | PYTHONUNBUFFERED=1 python3 -m verl.trainer.main_ppo \
27 | data.train_files=$TRAIN_DATA_DIR/train.parquet \
28 | data.val_files=$TEST_DATA_DIR/test.parquet \
29 | data.train_data_num=null \
30 | data.val_data_num=null \
31 | data.train_batch_size=512 \
32 | data.val_batch_size=256 \
33 | data.max_prompt_length=4096 \
34 | data.max_response_length=500 \
35 | data.max_start_length=2048 \
36 | data.max_obs_length=500 \
37 | data.shuffle_train_dataloader=True \
38 | algorithm.adv_estimator=grpo \
39 | actor_rollout_ref.model.path=$BASE_MODEL \
40 | actor_rollout_ref.model.enable_gradient_checkpointing=true \
41 | actor_rollout_ref.model.use_remove_padding=True \
42 | actor_rollout_ref.actor.optim.lr=1e-6 \
43 | actor_rollout_ref.actor.optim.lr_warmup_steps_ratio=0.285 \
44 | actor_rollout_ref.actor.use_kl_loss=true \
45 | actor_rollout_ref.actor.ppo_mini_batch_size=256 \
46 | actor_rollout_ref.actor.ppo_micro_batch_size=64 \
47 | actor_rollout_ref.actor.fsdp_config.param_offload=true \
48 | actor_rollout_ref.actor.fsdp_config.grad_offload=true \
49 | actor_rollout_ref.actor.fsdp_config.optimizer_offload=true \
50 | actor_rollout_ref.rollout.log_prob_micro_batch_size=128 \
51 | actor_rollout_ref.rollout.tensor_model_parallel_size=1 \
52 | actor_rollout_ref.rollout.name=vllm \
53 | actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
54 | actor_rollout_ref.ref.log_prob_micro_batch_size=128 \
55 | actor_rollout_ref.ref.fsdp_config.param_offload=True \
56 | actor_rollout_ref.actor.kl_loss_coef=0.001 \
57 | actor_rollout_ref.actor.kl_loss_type=low_var_kl \
58 | algorithm.no_think_rl=false \
59 | actor_rollout_ref.rollout.n_agent=5 \
60 | actor_rollout_ref.rollout.temperature=1 \
61 | actor_rollout_ref.actor.state_masking=true \
62 | trainer.logger=['wandb'] \
63 | +trainer.val_only=false \
64 | +trainer.val_before_train=true \
65 | trainer.default_hdfs_dir=null \
66 | trainer.n_gpus_per_node=8 \
67 | trainer.nnodes=1 \
68 | trainer.save_freq=100 \
69 | trainer.test_freq=100 \
70 | trainer.project_name=$WAND_PROJECT \
71 | trainer.experiment_name=$EXPERIMENT_NAME \
72 | trainer.total_epochs=15 \
73 | trainer.total_training_steps=1005 \
74 | trainer.default_hdfs_dir=null \
75 | trainer.default_local_dir=verl_checkpoints/$EXPERIMENT_NAME \
76 | max_turns=4 \
77 | retriever.url="http://127.0.0.1:8000/retrieve" \
78 | retriever.topk=3 \
79 | 2>&1 | tee $EXPERIMENT_NAME.log
80 |
--------------------------------------------------------------------------------
/scripts/nq_hotpotqa/v0.2/train_ppo.sh:
--------------------------------------------------------------------------------
1 | data_name=nq_hotpotqa_train
2 |
3 | export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
4 | export DATA_DIR=data/${data_name} # first download the data from https://huggingface.co/datasets/PeterJinGo/nq_hotpotqa_train
5 |
6 | WAND_PROJECT="Search-R1"
7 |
8 | # export BASE_MODEL='Qwen/Qwen2.5-3B'
9 | # export EXPERIMENT_NAME=${train_data}-${test_data}-search-r1-ppo-qwen2.5-3b-em
10 | # export BASE_MODEL='Qwen/Qwen2.5-3B-Instruct'
11 | # export EXPERIMENT_NAME=${train_data}-${test_data}-search-r1-ppo-qwen2.5-3b-it-em
12 | export BASE_MODEL='Qwen/Qwen2.5-7B'
13 | export EXPERIMENT_NAME=${train_data}-${test_data}-search-r1-ppo-qwen2.5-7b-em
14 | # export BASE_MODEL='Qwen/Qwen2.5-7B-Instruct'
15 | # export EXPERIMENT_NAME=${train_data}-${test_data}-search-r1-ppo-qwen2.5-7b-it-em
16 | # export BASE_MODEL='Qwen/Qwen2.5-14B'
17 | # export EXPERIMENT_NAME=${train_data}-${test_data}-search-r1-ppo-qwen2.5-14b-em
18 | # export BASE_MODEL='Qwen/Qwen2.5-14B-Instruct'
19 | # export EXPERIMENT_NAME=${train_data}-${test_data}-search-r1-ppo-qwen2.5-14b-it-em
20 |
21 | # set -x
22 | export VLLM_ATTENTION_BACKEND=XFORMERS # vllm + qwen2-7b with flash_attn has some issues
23 |
24 | # max_prompt_length = (config['training']['max_start_length'] + config['training']['max_response_length'] * (config['training']['max_turns'] - 1) + config['training']['max_obs_length'] * config['training']['max_turns'])
25 |
26 | PYTHONUNBUFFERED=1 python3 -m verl.trainer.main_ppo \
27 | data.train_files=$TRAIN_DATA_DIR/train.parquet \
28 | data.val_files=$TEST_DATA_DIR/test.parquet \
29 | data.train_data_num=null \
30 | data.val_data_num=null \
31 | data.train_batch_size=512 \
32 | data.val_batch_size=256 \
33 | data.max_prompt_length=4096 \
34 | data.max_response_length=500 \
35 | data.max_start_length=2048 \
36 | data.max_obs_length=500 \
37 | data.shuffle_train_dataloader=True \
38 | algorithm.adv_estimator=gae \
39 | actor_rollout_ref.model.path=$BASE_MODEL \
40 | actor_rollout_ref.actor.optim.lr=1e-6 \
41 | actor_rollout_ref.model.enable_gradient_checkpointing=true \
42 | actor_rollout_ref.model.use_remove_padding=True \
43 | actor_rollout_ref.actor.optim.lr_warmup_steps_ratio=0.285 \
44 | actor_rollout_ref.actor.ppo_mini_batch_size=256 \
45 | actor_rollout_ref.actor.ppo_micro_batch_size=64 \
46 | actor_rollout_ref.actor.fsdp_config.param_offload=true \
47 | actor_rollout_ref.actor.fsdp_config.grad_offload=true \
48 | actor_rollout_ref.actor.fsdp_config.optimizer_offload=true \
49 | actor_rollout_ref.rollout.log_prob_micro_batch_size=128 \
50 | actor_rollout_ref.rollout.tensor_model_parallel_size=1 \
51 | actor_rollout_ref.rollout.name=vllm \
52 | actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
53 | actor_rollout_ref.ref.log_prob_micro_batch_size=128 \
54 | actor_rollout_ref.ref.fsdp_config.param_offload=True \
55 | actor_rollout_ref.rollout.n_agent=1 \
56 | actor_rollout_ref.rollout.temperature=1 \
57 | actor_rollout_ref.rollout.top_p=1.0 \
58 | actor_rollout_ref.actor.state_masking=true \
59 | critic.optim.lr=1e-5 \
60 | critic.model.use_remove_padding=True \
61 | critic.optim.lr_warmup_steps_ratio=0.015 \
62 | critic.model.path=$BASE_MODEL \
63 | critic.model.enable_gradient_checkpointing=true \
64 | critic.ppo_micro_batch_size=8 \
65 | critic.model.fsdp_config.param_offload=true \
66 | critic.model.fsdp_config.grad_offload=true \
67 | critic.model.fsdp_config.optimizer_offload=true \
68 | algorithm.kl_ctrl.kl_coef=0.001 \
69 | algorithm.no_think_rl=false \
70 | trainer.critic_warmup=0 \
71 | trainer.logger=['wandb'] \
72 | +trainer.val_only=false \
73 | +trainer.val_before_train=true \
74 | trainer.default_hdfs_dir=null \
75 | trainer.n_gpus_per_node=8 \
76 | trainer.nnodes=1 \
77 | trainer.save_freq=100 \
78 | trainer.test_freq=100 \
79 | trainer.project_name=$WAND_PROJECT \
80 | trainer.experiment_name=$EXPERIMENT_NAME \
81 | trainer.total_epochs=15 \
82 | trainer.total_training_steps=1005 \
83 | trainer.default_hdfs_dir=null \
84 | trainer.default_local_dir=verl_checkpoints/$EXPERIMENT_NAME \
85 | max_turns=4 \
86 | retriever.url="http://127.0.0.1:8000/retrieve" \
87 | retriever.topk=3 \
88 | 2>&1 | tee $EXPERIMENT_NAME.log
89 |
--------------------------------------------------------------------------------
/scripts/upload.py:
--------------------------------------------------------------------------------
1 | import os
2 | from huggingface_hub import upload_file
3 |
4 | repo_id = "PeterJinGo/wiki-18-e5-index"
5 | path = "/home/peterjin/mnt/index/wiki-18"
6 | for file in ["part_aa", "part_ab"]:
7 | upload_file(
8 | path_or_fileobj=os.path.join(path, file), # File path
9 | path_in_repo=file, # Destination filename in the repo
10 | repo_id=repo_id, # Your dataset repo ID
11 | repo_type="dataset"
12 | )
13 |
--------------------------------------------------------------------------------
/scripts/upload.sh:
--------------------------------------------------------------------------------
1 |
2 | index=/home/peterjin/mnt/index/wiki-18/e5_Flat.index
3 |
4 | split -b 40G $index part_
5 |
6 | python upload.py
7 |
--------------------------------------------------------------------------------
/search_r1/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PeterGriffinJin/Search-R1/67fcca7fb311a9ee0f5f32c98bc2b24cefc094da/search_r1/__init__.py
--------------------------------------------------------------------------------
/search_r1/llm_agent/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PeterGriffinJin/Search-R1/67fcca7fb311a9ee0f5f32c98bc2b24cefc094da/search_r1/llm_agent/__init__.py
--------------------------------------------------------------------------------
/search_r1/llm_agent/tensor_helper.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from typing import Dict, Tuple, List
3 | from dataclasses import dataclass
4 |
5 | @dataclass
6 | class TensorConfig:
7 | pad_token_id: int
8 | max_prompt_length: int
9 | max_obs_length: int
10 | max_start_length: int
11 |
12 | class TensorHelper:
13 | def __init__(self, config: TensorConfig):
14 | self.config = config
15 |
16 | def cut_to_effective_len(self, tensor_dict: Dict[str, torch.Tensor],
17 | keys: List[str], cut_left: bool = True) -> Dict[str, torch.Tensor]:
18 | """Cut tensors to their effective length based on attention mask."""
19 | effective_len = tensor_dict['attention_mask'].sum(dim=1).max()
20 | result = tensor_dict.copy()
21 |
22 | for key in keys:
23 | if cut_left:
24 | result[key] = tensor_dict[key][:, -effective_len:]
25 | else:
26 | result[key] = tensor_dict[key][:, :effective_len]
27 | return result
28 |
29 | def convert_pad_structure(self, tensor: torch.Tensor, pad_to_left: bool = True) -> Tuple[torch.Tensor, torch.Tensor]:
30 | """Convert padding structure and return sorted tensor with indices."""
31 | mask = tensor != self.config.pad_token_id if pad_to_left else tensor == self.config.pad_token_id
32 | sorted_indices = mask.to(torch.int64).argsort(dim=1, stable=True)
33 | return tensor.gather(1, sorted_indices), sorted_indices
34 |
35 | def create_attention_mask(self, input_ids: torch.Tensor) -> torch.Tensor:
36 | """Create attention mask from input ids."""
37 | return torch.where(input_ids != self.config.pad_token_id, 1, 0)
38 |
39 | def create_position_ids(self, attention_mask: torch.Tensor) -> torch.Tensor:
40 | """Create position ids from attention mask."""
41 | return (torch.cumsum(attention_mask, dim=1) - 1) * attention_mask
42 |
43 | def concatenate_with_padding(self, tensors: List[torch.Tensor],
44 | pad_to_left: bool = True) -> torch.Tensor:
45 | """Concatenate tensors and handle padding."""
46 | concatenated = torch.cat(tensors, dim=1)
47 | padded_tensor, _ = self.convert_pad_structure(concatenated, pad_to_left)
48 | return padded_tensor
49 |
50 | def _example_level_pad(self, responses: torch.Tensor,
51 | responses_str: List[str],
52 | active_mask: torch.Tensor) -> Tuple[torch.Tensor, List[str]]:
53 | """
54 | Pad responses for non-active examples with pad tokens.
55 | """
56 | assert active_mask.sum() == responses.shape[0]
57 | # Create masked responses tensor
58 | batch_size = active_mask.shape[0]
59 | seq_len = responses.shape[1]
60 | padded_responses = torch.full(
61 | (batch_size, seq_len), self.config.pad_token_id,
62 | dtype=responses.dtype, device=responses.device
63 | )
64 | padded_responses[active_mask] = responses
65 |
66 | # Create masked response strings
67 | padded_responses_str = [""] * batch_size
68 |
69 | s = 0
70 | for i, is_active in enumerate(active_mask):
71 | if is_active:
72 | padded_responses_str[i] = responses_str[s]
73 | s += 1
74 |
75 | return padded_responses, padded_responses_str
--------------------------------------------------------------------------------
/search_r1/search/build_index.sh:
--------------------------------------------------------------------------------
1 |
2 | corpus_file=/your/corpus/jsonl/file # jsonl
3 | save_dir=/the/path/to/save/index
4 | retriever_name=e5 # this is for indexing naming
5 | retriever_model=intfloat/e5-base-v2
6 |
7 | # change faiss_type to HNSW32/64/128 for ANN indexing
8 | # change retriever_name to bm25 for BM25 indexing
9 | CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python index_builder.py \
10 | --retrieval_method $retriever_name \
11 | --model_path $retriever_model \
12 | --corpus_path $corpus_file \
13 | --save_dir $save_dir \
14 | --use_fp16 \
15 | --max_length 256 \
16 | --batch_size 512 \
17 | --pooling_method mean \
18 | --faiss_type Flat \
19 | --save_embedding
20 |
--------------------------------------------------------------------------------
/search_r1/search/retrieval.sh:
--------------------------------------------------------------------------------
1 |
2 | DATA_NAME=nq
3 |
4 | DATASET_PATH="/home/peterjin/mnt/data/$DATA_NAME"
5 |
6 | SPLIT='test'
7 | TOPK=3
8 |
9 | INDEX_PATH=/home/peterjin/mnt/index/wiki-18
10 | CORPUS_PATH=/home/peterjin/mnt/data/retrieval-corpus/wiki-18.jsonl
11 | SAVE_NAME=e5_${TOPK}_wiki18.json
12 |
13 | # INDEX_PATH=/home/peterjin/rm_retrieval_corpus/index/wiki-21
14 | # CORPUS_PATH=/home/peterjin/rm_retrieval_corpus/corpora/wiki/enwiki-dec2021/text-list-100-sec.jsonl
15 | # SAVE_NAME=e5_${TOPK}_wiki21.json
16 |
17 | CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python retrieval.py --retrieval_method e5 \
18 | --retrieval_topk $TOPK \
19 | --index_path $INDEX_PATH \
20 | --corpus_path $CORPUS_PATH \
21 | --dataset_path $DATASET_PATH \
22 | --data_split $SPLIT \
23 | --retrieval_model_path "intfloat/e5-base-v2" \
24 | --retrieval_pooling_method "mean" \
25 | --retrieval_batch_size 512 \
26 |
--------------------------------------------------------------------------------
/search_r1/search/retrieval_request.py:
--------------------------------------------------------------------------------
1 | import requests
2 |
3 | # URL for your local FastAPI server
4 | url = "http://127.0.0.1:8000/retrieve"
5 |
6 | # Example payload
7 | payload = {
8 | "queries": ["What is the capital of France?", "Explain neural networks."] * 200,
9 | "topk": 5,
10 | "return_scores": True
11 | }
12 |
13 | # Send POST request
14 | response = requests.post(url, json=payload)
15 |
16 | # Raise an exception if the request failed
17 | response.raise_for_status()
18 |
19 | # Get the JSON response
20 | retrieved_data = response.json()
21 |
22 | print("Response from server:")
23 | print(retrieved_data)
24 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | # setup.py is the fallback installation script when pyproject.toml does not work
16 | from setuptools import setup, find_packages
17 | import os
18 |
19 | version_folder = os.path.dirname(os.path.join(os.path.abspath(__file__)))
20 |
21 | with open(os.path.join(version_folder, 'verl/version/version')) as f:
22 | __version__ = f.read().strip()
23 |
24 |
25 | with open('requirements.txt') as f:
26 | required = f.read().splitlines()
27 | install_requires = [item.strip() for item in required if item.strip()[0] != '#']
28 |
29 | extras_require = {
30 | 'test': ['pytest', 'yapf']
31 | }
32 |
33 | from pathlib import Path
34 | this_directory = Path(__file__).parent
35 | long_description = (this_directory / "README.md").read_text()
36 |
37 | setup(
38 | name='verl',
39 | version=__version__,
40 | package_dir={'': '.'},
41 | packages=find_packages(where='.'),
42 | url='https://github.com/volcengine/verl',
43 | license='Apache 2.0',
44 | author='Bytedance - Seed - MLSys',
45 | author_email='zhangchi.usc1992@bytedance.com, gmsheng@connect.hku.hk',
46 | description='veRL: Volcano Engine Reinforcement Learning for LLM',
47 | install_requires=install_requires,
48 | extras_require=extras_require,
49 | package_data={'': ['version/*'],
50 | 'verl': ['trainer/config/*.yaml'],},
51 | include_package_data=True,
52 | long_description=long_description,
53 | long_description_content_type='text/markdown'
54 | )
--------------------------------------------------------------------------------
/train_grpo.sh:
--------------------------------------------------------------------------------
1 | export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
2 | export DATA_DIR='data/nq_search'
3 |
4 | WAND_PROJECT='Search-R1'
5 |
6 | # export BASE_MODEL='meta-llama/Llama-3.2-3B'
7 | # export EXPERIMENT_NAME=nq-search-r1-grpo-llama3.2-3b-em
8 | # export BASE_MODEL='meta-llama/Llama-3.2-3B-Instruct'
9 | # export EXPERIMENT_NAME=nq-search-r1-grpo-llama3.2-3b-it-em
10 | # export BASE_MODEL='meta-llama/Llama-3.1-8B'
11 | # export EXPERIMENT_NAME=nq-search-r1-grpo-llama3.1-8b-em
12 | # export BASE_MODEL='meta-llama/Llama-3.1-8B-Instruct'
13 | # export EXPERIMENT_NAME=nq-search-r1-grpo-llama3.1-8b-it-em
14 |
15 | export BASE_MODEL='Qwen/Qwen2.5-3B'
16 | export EXPERIMENT_NAME=nq-search-r1-grpo-qwen2.5-3b-em
17 | # export BASE_MODEL='Qwen/Qwen2.5-3B-Instruct'
18 | # export EXPERIMENT_NAME=nq-search-r1-grpo-qwen2.5-3b-it-em
19 | # export BASE_MODEL='Qwen/Qwen2.5-7B'
20 | # export EXPERIMENT_NAME=nq-search-r1-grpo-qwen2.5-7b-em
21 | # export BASE_MODEL='Qwen/Qwen2.5-7B-Instruct'
22 | # export EXPERIMENT_NAME=nq-search-r1-grpo-qwen2.5-7b-it-em
23 |
24 | # set -x
25 | export VLLM_ATTENTION_BACKEND=XFORMERS # vllm + qwen2-7b with flash_attn has some issues
26 |
27 | # max_prompt_length = (config['training']['max_start_length'] + config['training']['max_response_length'] * (config['training']['max_turns'] - 1) + config['training']['max_obs_length'] * config['training']['max_turns'])
28 |
29 | PYTHONUNBUFFERED=1 python3 -m verl.trainer.main_ppo \
30 | data.train_files=$TRAIN_DATA_DIR/train.parquet \
31 | data.val_files=$TEST_DATA_DIR/test.parquet \
32 | data.train_data_num=null \
33 | data.val_data_num=null \
34 | data.train_batch_size=512 \
35 | data.val_batch_size=256 \
36 | data.max_prompt_length=4096 \
37 | data.max_response_length=500 \
38 | data.max_start_length=2048 \
39 | data.max_obs_length=500 \
40 | data.shuffle_train_dataloader=True \
41 | algorithm.adv_estimator=grpo \
42 | actor_rollout_ref.model.path=$BASE_MODEL \
43 | actor_rollout_ref.model.enable_gradient_checkpointing=true \
44 | actor_rollout_ref.model.use_remove_padding=True \
45 | actor_rollout_ref.actor.optim.lr=1e-6 \
46 | actor_rollout_ref.actor.optim.lr_warmup_steps_ratio=0.285 \
47 | actor_rollout_ref.actor.use_kl_loss=true \
48 | actor_rollout_ref.actor.ppo_mini_batch_size=256 \
49 | actor_rollout_ref.actor.ppo_micro_batch_size=64 \
50 | actor_rollout_ref.actor.fsdp_config.param_offload=true \
51 | actor_rollout_ref.actor.fsdp_config.grad_offload=true \
52 | actor_rollout_ref.actor.fsdp_config.optimizer_offload=true \
53 | actor_rollout_ref.rollout.log_prob_micro_batch_size=128 \
54 | actor_rollout_ref.rollout.tensor_model_parallel_size=1 \
55 | actor_rollout_ref.rollout.name=vllm \
56 | actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
57 | actor_rollout_ref.ref.log_prob_micro_batch_size=128 \
58 | actor_rollout_ref.ref.fsdp_config.param_offload=True \
59 | actor_rollout_ref.actor.kl_loss_coef=0.001 \
60 | actor_rollout_ref.actor.kl_loss_type=low_var_kl \
61 | algorithm.no_think_rl=false \
62 | actor_rollout_ref.rollout.n_agent=5 \
63 | actor_rollout_ref.rollout.temperature=1 \
64 | actor_rollout_ref.actor.state_masking=true \
65 | trainer.logger=['wandb'] \
66 | +trainer.val_only=false \
67 | +trainer.val_before_train=true \
68 | trainer.default_hdfs_dir=null \
69 | trainer.n_gpus_per_node=8 \
70 | trainer.nnodes=1 \
71 | trainer.save_freq=100 \
72 | trainer.test_freq=50 \
73 | trainer.project_name=$WAND_PROJECT \
74 | trainer.experiment_name=$EXPERIMENT_NAME \
75 | trainer.total_epochs=15 \
76 | trainer.total_training_steps=1005 \
77 | trainer.default_hdfs_dir=null \
78 | trainer.default_local_dir=verl_checkpoints/$EXPERIMENT_NAME \
79 | max_turns=2 \
80 | retriever.url="http://127.0.0.1:8000/retrieve" \
81 | retriever.topk=3 \
82 | 2>&1 | tee $EXPERIMENT_NAME.log
--------------------------------------------------------------------------------
/train_ppo.sh:
--------------------------------------------------------------------------------
1 | export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
2 | export DATA_DIR='data/nq_search'
3 |
4 | WAND_PROJECT='Search-R1'
5 |
6 | export BASE_MODEL='meta-llama/Llama-3.2-3B'
7 | export EXPERIMENT_NAME=nq-search-r1-ppo-llama3.2-3b-em
8 | # export BASE_MODEL='meta-llama/Llama-3.2-3B-Instruct'
9 | # export EXPERIMENT_NAME=nq-search-r1-ppo-llama3.2-3b-it-em
10 | # export BASE_MODEL='meta-llama/Llama-3.1-8B'
11 | # export EXPERIMENT_NAME=nq-search-r1-ppo-llama3.1-8b-em
12 | # export BASE_MODEL='meta-llama/Llama-3.1-8B-Instruct'
13 | # export EXPERIMENT_NAME=nq-search-r1-ppo-llama3.1-8b-it-em
14 |
15 | # export BASE_MODEL='Qwen/Qwen2.5-3B'
16 | # export EXPERIMENT_NAME=nq-search-r1-ppo-qwen2.5-3b-em
17 | # export BASE_MODEL='Qwen/Qwen2.5-3B-Instruct'
18 | # export EXPERIMENT_NAME=nq-search-r1-ppo-qwen2.5-3b-it-em
19 | # export BASE_MODEL='Qwen/Qwen2.5-7B'
20 | # export EXPERIMENT_NAME=nq-search-r1-ppo-qwen2.5-7b-em
21 | # export BASE_MODEL='Qwen/Qwen2.5-7B-Instruct'
22 | # export EXPERIMENT_NAME=nq-search-r1-ppo-qwen2.5-7b-it-em
23 |
24 | # set -x
25 | export VLLM_ATTENTION_BACKEND=XFORMERS # vllm + qwen2-7b with flash_attn has some issues
26 |
27 | # max_prompt_length = (config['training']['max_start_length'] + config['training']['max_response_length'] * (config['training']['max_turns'] - 1) + config['training']['max_obs_length'] * config['training']['max_turns'])
28 |
29 | PYTHONUNBUFFERED=1 python3 -m verl.trainer.main_ppo \
30 | data.train_files=$DATA_DIR/train.parquet \
31 | data.val_files=$DATA_DIR/test.parquet \
32 | data.train_data_num=null \
33 | data.val_data_num=null \
34 | data.train_batch_size=512 \
35 | data.val_batch_size=256 \
36 | data.max_prompt_length=4096 \
37 | data.max_response_length=500 \
38 | data.max_start_length=2048 \
39 | data.max_obs_length=500 \
40 | data.shuffle_train_dataloader=True \
41 | algorithm.adv_estimator=gae \
42 | actor_rollout_ref.model.path=$BASE_MODEL \
43 | actor_rollout_ref.actor.optim.lr=1e-6 \
44 | actor_rollout_ref.model.enable_gradient_checkpointing=true \
45 | actor_rollout_ref.model.use_remove_padding=True \
46 | actor_rollout_ref.actor.optim.lr_warmup_steps_ratio=0.285 \
47 | actor_rollout_ref.actor.ppo_mini_batch_size=256 \
48 | actor_rollout_ref.actor.ppo_micro_batch_size=64 \
49 | actor_rollout_ref.actor.fsdp_config.param_offload=true \
50 | actor_rollout_ref.actor.fsdp_config.grad_offload=true \
51 | actor_rollout_ref.actor.fsdp_config.optimizer_offload=true \
52 | actor_rollout_ref.rollout.log_prob_micro_batch_size=128 \
53 | actor_rollout_ref.rollout.tensor_model_parallel_size=1 \
54 | actor_rollout_ref.rollout.name=vllm \
55 | actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
56 | actor_rollout_ref.ref.log_prob_micro_batch_size=128 \
57 | actor_rollout_ref.ref.fsdp_config.param_offload=True \
58 | actor_rollout_ref.rollout.n_agent=1 \
59 | actor_rollout_ref.rollout.temperature=1 \
60 | actor_rollout_ref.actor.state_masking=true \
61 | critic.optim.lr=1e-5 \
62 | critic.model.use_remove_padding=True \
63 | critic.optim.lr_warmup_steps_ratio=0.015 \
64 | critic.model.path=$BASE_MODEL \
65 | critic.model.enable_gradient_checkpointing=true \
66 | critic.ppo_micro_batch_size=8 \
67 | critic.model.fsdp_config.param_offload=true \
68 | critic.model.fsdp_config.grad_offload=true \
69 | critic.model.fsdp_config.optimizer_offload=true \
70 | algorithm.kl_ctrl.kl_coef=0.001 \
71 | algorithm.no_think_rl=false \
72 | trainer.critic_warmup=0 \
73 | trainer.logger=['wandb'] \
74 | +trainer.val_only=false \
75 | +trainer.val_before_train=true \
76 | trainer.default_hdfs_dir=null \
77 | trainer.n_gpus_per_node=8 \
78 | trainer.nnodes=1 \
79 | trainer.save_freq=100 \
80 | trainer.test_freq=50 \
81 | trainer.project_name=$WAND_PROJECT \
82 | trainer.experiment_name=$EXPERIMENT_NAME \
83 | trainer.total_epochs=15 \
84 | trainer.total_training_steps=1005 \
85 | trainer.default_hdfs_dir=null \
86 | trainer.default_local_dir=verl_checkpoints/$EXPERIMENT_NAME \
87 | max_turns=2 \
88 | retriever.url="http://127.0.0.1:8000/retrieve" \
89 | retriever.topk=3 \
90 | 2>&1 | tee $EXPERIMENT_NAME.log
--------------------------------------------------------------------------------
/verl/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | import os
16 |
17 | version_folder = os.path.dirname(os.path.join(os.path.abspath(__file__)))
18 |
19 | with open(os.path.join(version_folder, 'version/version')) as f:
20 | __version__ = f.read().strip()
21 |
22 | from .protocol import DataProto
23 |
24 | from .utils.logging_utils import set_basic_config
25 | import logging
26 |
27 | set_basic_config(level=logging.WARNING)
28 |
--------------------------------------------------------------------------------
/verl/models/README.md:
--------------------------------------------------------------------------------
1 | # Models
2 | Common 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.
3 | ## Adding a New Huggingface Model
4 | ### Step 1: Copy the model file from HF to verl
5 | - Add a new file under verl/models/hf
6 | - Copy ONLY the model file from huggingface/transformers/models to verl/models/hf
7 |
8 | ### Step 2: Modify the model file to use packed inputs
9 | - Remove all the code related to inference (kv cache)
10 | - Modify the inputs to include only
11 | - input_ids (total_nnz,)
12 | - cu_seqlens (total_nnz + 1,)
13 | - max_seqlen_in_batch: int
14 | - Note that this requires using flash attention with causal mask.
15 |
16 | ### Step 2.5: Add tests
17 | - Add a test to compare this version and the huggingface version
18 | - Following the infrastructure and add tests to tests/models/hf
19 |
20 | ### Step 3: Add a function to apply tensor parallelism
21 | - Please follow
22 | - https://pytorch.org/docs/stable/distributed.tensor.parallel.html
23 | - https://pytorch.org/tutorials/intermediate/TP_tutorial.html
24 | - General comments
25 | - 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.
26 |
27 | ### Step 4: Add a function to apply data parallelism
28 | - Please use FSDP2 APIs
29 | - See demo here https://github.com/pytorch/torchtitan/blob/main/torchtitan/parallelisms/parallelize_llama.py#L413
30 |
31 | ### Step 5: Add a function to apply pipeline parallelism
32 | - Comes in Pytorch 2.4
33 | - Currently only in alpha in nightly version
34 | - Check torchtitan for more details
35 |
36 |
--------------------------------------------------------------------------------
/verl/models/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/models/llama/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/models/llama/megatron/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from .modeling_llama_megatron import (
16 | # original model with megatron
17 | ParallelLlamaModel,
18 | ParallelLlamaForCausalLM,
19 | # rmpad with megatron
20 | ParallelLlamaForCausalLMRmPad,
21 | ParallelLlamaForValueRmPad,
22 | # rmpad with megatron and pipeline parallelism
23 | ParallelLlamaForCausalLMRmPadPP,
24 | ParallelLlamaForValueRmPadPP)
25 |
--------------------------------------------------------------------------------
/verl/models/llama/megatron/checkpoint_utils/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/models/llama/megatron/layers/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from .parallel_attention import ParallelLlamaAttention
16 | from .parallel_decoder import ParallelLlamaDecoderLayer, ParallelLlamaDecoderLayerRmPad
17 | from .parallel_mlp import ParallelLlamaMLP
18 | from .parallel_rmsnorm import ParallelLlamaRMSNorm
19 |
--------------------------------------------------------------------------------
/verl/models/llama/megatron/layers/parallel_linear.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | # Copyright 2023 The vLLM team.
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | # Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/linear.py
15 |
16 | from typing import Optional, Tuple
17 |
18 | from megatron.core import tensor_parallel
19 |
20 |
21 | class QKVParallelLinear(tensor_parallel.ColumnParallelLinear):
22 |
23 | def __init__(self,
24 | input_size,
25 | num_heads,
26 | num_key_value_heads,
27 | head_dim,
28 | *,
29 | bias=True,
30 | gather_output=True,
31 | skip_bias_add=False,
32 | **kwargs):
33 | # Keep input parameters, and already restrict the head numbers
34 | self.input_size = input_size
35 | self.q_output_size = num_heads * head_dim
36 | self.kv_output_size = num_key_value_heads * head_dim
37 | self.head_dim = head_dim
38 | self.gather_output = gather_output
39 | self.skip_bias_add = skip_bias_add
40 |
41 | input_size = self.input_size
42 | output_size = (num_heads + 2 * num_key_value_heads) * self.head_dim
43 |
44 | super().__init__(input_size=input_size,
45 | output_size=output_size,
46 | bias=bias,
47 | gather_output=gather_output,
48 | skip_bias_add=skip_bias_add,
49 | **kwargs)
50 |
51 |
52 | class MergedColumnParallelLinear(tensor_parallel.ColumnParallelLinear):
53 |
54 | def __init__(self,
55 | input_size,
56 | gate_ouput_size,
57 | up_output_size,
58 | *,
59 | bias=True,
60 | gather_output=True,
61 | skip_bias_add=False,
62 | **kwargs):
63 | # Keep input parameters, and already restrict the head numbers
64 | self.input_size = input_size
65 | self.output_size = gate_ouput_size + up_output_size
66 | self.gather_output = gather_output
67 | self.skip_bias_add = skip_bias_add
68 |
69 | super().__init__(input_size=self.input_size,
70 | output_size=self.output_size,
71 | bias=bias,
72 | gather_output=gather_output,
73 | skip_bias_add=skip_bias_add,
74 | **kwargs)
75 |
--------------------------------------------------------------------------------
/verl/models/llama/megatron/layers/parallel_mlp.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3 | #
4 | # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5 | # and OPT implementations in this library. It has been modified from its
6 | # original forms to accommodate minor architectural differences compared
7 | # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8 | #
9 | # Licensed under the Apache License, Version 2.0 (the "License");
10 | # you may not use this file except in compliance with the License.
11 | # You may obtain a copy of the License at
12 | #
13 | # http://www.apache.org/licenses/LICENSE-2.0
14 | #
15 | # Unless required by applicable law or agreed to in writing, software
16 | # distributed under the License is distributed on an "AS IS" BASIS,
17 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 | # See the License for the specific language governing permissions and
19 | # limitations under the License.
20 |
21 | from megatron.core import parallel_state as mpu
22 | from megatron.core import tensor_parallel
23 | from megatron.core import ModelParallelConfig
24 | from torch import nn
25 | from transformers.activations import ACT2FN
26 | from verl.models.llama.megatron.layers.parallel_linear import MergedColumnParallelLinear
27 |
28 | from verl.utils.megatron import tensor_parallel as tp_utils
29 |
30 |
31 | class ParallelLlamaMLP(nn.Module):
32 |
33 | def __init__(self, config, megatron_config: ModelParallelConfig = None) -> None:
34 | super().__init__()
35 | self.config = config
36 | self.hidden_size = config.hidden_size
37 | self.intermediate_size = config.intermediate_size
38 | # The weight is only [hidden_size, intermediate_size // model_parallel_world_size]
39 |
40 | column_kwargs = tp_utils.get_default_kwargs_for_column_parallel_linear()
41 | row_kwargs = tp_utils.get_default_kwargs_for_row_parallel_linear()
42 |
43 | if megatron_config is not None:
44 | assert column_kwargs.get('config', False), 'must have ModelParallelConfig'
45 | assert row_kwargs.get('config', False), 'must have ModelParallelConfig'
46 | tp_utils.update_kwargs_with_config(row_kwargs, megatron_config)
47 | tp_utils.update_kwargs_with_config(column_kwargs, megatron_config)
48 |
49 | tp_size = mpu.get_tensor_model_parallel_world_size()
50 |
51 | self.gate_up_proj = MergedColumnParallelLinear(
52 | input_size=self.hidden_size,
53 | gate_ouput_size=self.intermediate_size,
54 | up_output_size=self.intermediate_size,
55 | bias=False,
56 | gather_output=False,
57 | skip_bias_add=False,
58 | **column_kwargs,
59 | )
60 | self.gate_size = self.intermediate_size // tp_size
61 |
62 | self.down_proj = tensor_parallel.RowParallelLinear(input_size=self.intermediate_size,
63 | output_size=self.hidden_size,
64 | bias=False,
65 | input_is_parallel=True,
66 | skip_bias_add=False,
67 | **row_kwargs)
68 |
69 | self.act_fn = ACT2FN[config.hidden_act]
70 |
71 | def forward(self, x):
72 | gate_up = self.gate_up_proj(x)[0]
73 | gate, up = gate_up.split(self.gate_size, dim=-1)
74 | return self.down_proj(self.act_fn(gate) * up)[0]
75 |
--------------------------------------------------------------------------------
/verl/models/llama/megatron/layers/parallel_rmsnorm.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | import numbers
16 | import torch
17 | from megatron.core import ModelParallelConfig
18 | from torch import nn
19 | from transformers import LlamaConfig
20 |
21 | from apex.normalization.fused_layer_norm import fused_rms_norm_affine
22 | from verl.utils.megatron import sequence_parallel as sp_utils
23 |
24 |
25 | class ParallelLlamaRMSNorm(nn.Module):
26 |
27 | def __init__(self, config: LlamaConfig, megatron_config: ModelParallelConfig):
28 | """
29 | LlamaRMSNorm is equivalent to T5LayerNorm
30 | """
31 | super().__init__()
32 | if isinstance(config.hidden_size, numbers.Integral):
33 | normalized_shape = (config.hidden_size,)
34 | self.normalized_shape = torch.Size(normalized_shape)
35 | self.weight = nn.Parameter(torch.ones(self.normalized_shape))
36 | self.variance_epsilon = config.rms_norm_eps
37 |
38 | if megatron_config.sequence_parallel:
39 | sp_utils.mark_parameter_as_sequence_parallel(self.weight)
40 |
41 | def forward(self, hidden_states):
42 | return fused_rms_norm_affine(input=hidden_states,
43 | weight=self.weight,
44 | normalized_shape=self.normalized_shape,
45 | eps=self.variance_epsilon,
46 | memory_efficient=True)
--------------------------------------------------------------------------------
/verl/models/registry.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | import importlib
16 | from typing import List, Optional, Type
17 |
18 | import torch.nn as nn
19 |
20 | # Supported models using HF Rmpad
21 | # TODO(sgm): HF may supported more than listed here, we should add more after testing
22 | from transformers import LlamaConfig, MistralConfig, GemmaConfig, Qwen2Config
23 |
24 | _REOVEPAD_MODELS = {'llama': LlamaConfig, 'mistral': MistralConfig, 'gemma': GemmaConfig, 'qwen2': Qwen2Config}
25 |
26 |
27 | def check_model_support_rmpad(model_type: str):
28 | assert isinstance(model_type, str)
29 | if not model_type in _REOVEPAD_MODELS.keys():
30 | raise ValueError(f"Model architecture {model_type} is not supported for now. "
31 | f"RMPad supported architectures: {_REOVEPAD_MODELS.keys()}."
32 | f"Please set `use_remove_padding=False` in the model config.")
33 |
34 |
35 | # Supported models in Megatron-LM
36 | # Architecture -> (module, class).
37 | _MODELS = {
38 | "LlamaForCausalLM":
39 | ("llama", ("ParallelLlamaForCausalLMRmPadPP", "ParallelLlamaForValueRmPadPP", "ParallelLlamaForCausalLMRmPad")),
40 | "MistralForCausalLM": ("mistral", ("ParallelMistralForCausalLMRmPadPP", "ParallelMistralForValueRmPadPP",
41 | "ParallelMistralForCausalLMRmPad"))
42 | }
43 |
44 |
45 | # return model class
46 | class ModelRegistry:
47 |
48 | @staticmethod
49 | def load_model_cls(model_arch: str, value=False) -> Optional[Type[nn.Module]]:
50 | if model_arch not in _MODELS:
51 | return None
52 |
53 | megatron = "megatron"
54 |
55 | module_name, model_cls_name = _MODELS[model_arch]
56 | if not value: # actor/ref
57 | model_cls_name = model_cls_name[0]
58 | elif value: # critic/rm
59 | model_cls_name = model_cls_name[1]
60 |
61 | module = importlib.import_module(f"verl.models.{module_name}.{megatron}.modeling_{module_name}_megatron")
62 | return getattr(module, model_cls_name, None)
63 |
64 | @staticmethod
65 | def get_supported_archs() -> List[str]:
66 | return list(_MODELS.keys())
67 |
--------------------------------------------------------------------------------
/verl/models/transformers/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/models/transformers/monkey_patch.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | Apply monkey-patch function to models
16 | """
17 |
18 | #### Open Source Models
19 | #### transformers version < 4.48
20 |
21 |
22 | def apply_monkey_patch_to_llama():
23 | from transformers.models.llama.modeling_llama import LlamaFlashAttention2
24 | from verl.models.transformers.llama import llama_flash_attn_forward
25 | LlamaFlashAttention2.forward = llama_flash_attn_forward
26 |
27 |
28 | def apply_monkey_patch_to_qwen2():
29 | from transformers.models.qwen2.modeling_qwen2 import Qwen2FlashAttention2
30 | from verl.models.transformers.qwen2 import qwen2_flash_attn_forward
31 | Qwen2FlashAttention2.forward = qwen2_flash_attn_forward
32 |
33 |
34 | _PATCH_NAME_TO_FUNC = {
35 | 'llama': apply_monkey_patch_to_llama,
36 | 'qwen2': apply_monkey_patch_to_qwen2,
37 | }
38 |
39 | from transformers import PretrainedConfig
40 |
41 |
42 | def apply_monkey_patch(config: PretrainedConfig, verbose=True):
43 | if not is_transformers_version_in_range("4.45.0", "4.47.1"):
44 | raise AssertionError("The installed `transformers` version doesn't support ulysses patch. "
45 | "Please install a version between 4.45.0 and 4.47.1 to use this ulysses feature.")
46 | success_apply_monkey_patch = False
47 | if config.model_type in _PATCH_NAME_TO_FUNC:
48 | _PATCH_NAME_TO_FUNC[config.model_type]()
49 | success_apply_monkey_patch = True
50 |
51 | if success_apply_monkey_patch and verbose:
52 | print(f'Applying monkey patch to model {config.model_type}')
53 | elif not success_apply_monkey_patch:
54 | raise NotImplementedError(f'Ulysses for model {config.model_type} is not implemented, \
55 | please set `ulysses_sequence_parallel_size=1`')
56 |
57 | return success_apply_monkey_patch
58 |
59 |
60 | from functools import lru_cache
61 | from packaging import version
62 | import importlib.metadata
63 |
64 |
65 | @lru_cache()
66 | def is_transformers_version_in_range(min_version: str, max_version: str) -> bool:
67 | try:
68 | # Get the installed version of the transformers library
69 | transformers_version = importlib.metadata.version("transformers")
70 | except importlib.metadata.PackageNotFoundError:
71 | raise ModuleNotFoundError("The `transformers` package is not installed.")
72 |
73 | # Check if the version is within the specified range
74 | return version.parse(min_version) <= version.parse(transformers_version) <= version.parse(max_version)
75 |
--------------------------------------------------------------------------------
/verl/models/weight_loader_registry.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
16 | def get_weight_loader(arch: str):
17 | from verl.models.llama.megatron.checkpoint_utils.llama_loader import load_state_dict_to_megatron_llama
18 | _MODEL_WEIGHT_MEGATRON_LOADER_REGISTRY = {'LlamaForCausalLM': load_state_dict_to_megatron_llama}
19 |
20 | if arch in _MODEL_WEIGHT_MEGATRON_LOADER_REGISTRY:
21 | return _MODEL_WEIGHT_MEGATRON_LOADER_REGISTRY[arch]
22 | raise ValueError(f"Model architectures {arch} are not supported for now. "
23 | f"Supported architectures: {_MODEL_WEIGHT_MEGATRON_LOADER_REGISTRY.keys()}")
24 |
--------------------------------------------------------------------------------
/verl/single_controller/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | import os
16 |
17 | version_folder = os.path.dirname(os.path.join(os.path.abspath(__file__)))
18 |
19 | with open(os.path.join(version_folder, 'version/version')) as f:
20 | __version__ = f.read().strip()
21 |
--------------------------------------------------------------------------------
/verl/single_controller/base/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from .worker import Worker
16 | from .worker_group import WorkerGroup, ClassWithInitArgs, ResourcePool
17 |
--------------------------------------------------------------------------------
/verl/single_controller/base/megatron/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/single_controller/base/megatron/worker.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | import os
16 | from dataclasses import dataclass
17 | from verl.single_controller.base.worker import Worker, DistRankInfo, DistGlobalInfo
18 |
19 |
20 | class MegatronWorker(Worker):
21 |
22 | def __init__(self, cuda_visible_devices=None) -> None:
23 | super().__init__(cuda_visible_devices)
24 |
25 | def get_megatron_global_info(self):
26 | from megatron.core import parallel_state as mpu
27 | tp_size = mpu.get_tensor_model_parallel_world_size()
28 | dp_size = mpu.get_data_parallel_world_size()
29 | pp_size = mpu.get_pipeline_model_parallel_world_size()
30 | info = DistGlobalInfo(tp_size=tp_size, dp_size=dp_size, pp_size=pp_size)
31 | return info
32 |
33 | def get_megatron_rank_info(self):
34 | from megatron.core import parallel_state as mpu
35 | tp_rank = mpu.get_tensor_model_parallel_rank()
36 | dp_rank = mpu.get_data_parallel_rank()
37 | pp_rank = mpu.get_pipeline_model_parallel_rank()
38 | info = DistRankInfo(tp_rank=tp_rank, dp_rank=dp_rank, pp_rank=pp_rank)
39 | return info
--------------------------------------------------------------------------------
/verl/single_controller/base/megatron/worker_group.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from typing import Dict
16 |
17 | from .worker import DistRankInfo, DistGlobalInfo
18 | from verl.single_controller.base import ResourcePool, WorkerGroup
19 |
20 |
21 | class MegatronWorkerGroup(WorkerGroup):
22 |
23 | def __init__(self, resource_pool: ResourcePool, **kwargs):
24 | super().__init__(resource_pool=resource_pool, **kwargs)
25 | self._megatron_rank_info = None
26 | self._megatron_global_info: DistGlobalInfo = None
27 |
28 | def init_megatron(self, default_megatron_kwargs: Dict = None):
29 | raise NotImplementedError(f"MegatronWorkerGroup.init_megatron should be overwritten")
30 |
31 | def get_megatron_rank_info(self, rank: int) -> DistRankInfo:
32 | assert 0 <= rank < self.world_size, f'rank must be from [0, world_size), Got {rank}'
33 | return self._megatron_rank_info[rank]
34 |
35 | @property
36 | def tp_size(self):
37 | assert self._megatron_global_info is not None, "MegatronWorkerGroup._megatron_global_info must be initialized"
38 | return self._megatron_global_info.tp_size
39 |
40 | @property
41 | def dp_size(self):
42 | assert self._megatron_global_info is not None, "MegatronWorkerGroup._megatron_global_info must be initialized"
43 | return self._megatron_global_info.dp_size
44 |
45 | @property
46 | def pp_size(self):
47 | assert self._megatron_global_info is not None, "MegatronWorkerGroup._megatron_global_info must be initialized"
48 | return self._megatron_global_info.pp_size
49 |
50 | def get_megatron_global_info(self):
51 | return self._megatron_global_info
52 |
--------------------------------------------------------------------------------
/verl/single_controller/base/register_center/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/single_controller/base/register_center/ray.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | import ray
16 |
17 |
18 | @ray.remote
19 | class WorkerGroupRegisterCenter:
20 |
21 | def __init__(self, rank_zero_info):
22 | self.rank_zero_info = rank_zero_info
23 |
24 | def get_rank_zero_info(self):
25 | return self.rank_zero_info
26 |
27 |
28 | def create_worker_group_register_center(name, info):
29 | return WorkerGroupRegisterCenter.options(name=name).remote(info)
30 |
--------------------------------------------------------------------------------
/verl/single_controller/ray/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from .base import RayResourcePool, RayClassWithInitArgs, RayWorkerGroup, create_colocated_worker_cls
16 | from .megatron import (MegatronRayWorkerGroup, DistRankInfo, DistGlobalInfo)
--------------------------------------------------------------------------------
/verl/single_controller/ray/megatron.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from typing import Dict, Optional
16 |
17 | import ray
18 |
19 | from .base import RayWorkerGroup, RayResourcePool, RayClassWithInitArgs
20 | from verl.single_controller.base.megatron.worker import DistRankInfo, DistGlobalInfo
21 | from verl.single_controller.base.megatron.worker_group import MegatronWorkerGroup
22 |
23 |
24 | # NOTE(sgm): for opensource megatron-core
25 | class NVMegatronRayWorkerGroup(RayWorkerGroup, MegatronWorkerGroup):
26 | """
27 | MegatronWorkerGroup will query each worker of its megatron rank info and store it inside the WorkerGroup
28 | so that the dispatcher can use it to dispatch data.
29 | """
30 |
31 | def __init__(self, resource_pool: RayResourcePool, ray_cls_with_init: RayClassWithInitArgs, **kwargs):
32 | super().__init__(resource_pool=resource_pool, ray_cls_with_init=ray_cls_with_init, **kwargs)
33 | self._megatron_rank_info: DistRankInfo = self.execute_all_sync(method_name='get_megatron_rank_info')
34 | self._megatron_global_info: DistGlobalInfo = ray.get(
35 | self.execute_rank_zero_async(method_name='get_megatron_global_info'))
36 |
37 |
38 | class MegatronRayWorkerGroup(RayWorkerGroup, MegatronWorkerGroup):
39 | """
40 | MegatronWorkerGroup will query each worker of its megatron rank info and store it inside the WorkerGroup
41 | so that the dispatcher can use it to dispatch data.
42 | """
43 |
44 | def __init__(self,
45 | resource_pool: RayResourcePool,
46 | ray_cls_with_init: RayClassWithInitArgs,
47 | default_megatron_kwargs: Dict = None,
48 | **kwargs):
49 | super().__init__(resource_pool=resource_pool,
50 | ray_cls_with_init=ray_cls_with_init,
51 | default_megatron_kwargs=default_megatron_kwargs,
52 | **kwargs)
53 | self.init_megatron(default_megatron_kwargs=default_megatron_kwargs)
54 | self._megatron_rank_info: DistRankInfo = self.execute_all_sync(method_name='get_megatron_rank_info')
55 | self._megatron_global_info: DistGlobalInfo = ray.get(
56 | self.execute_rank_zero_async(method_name='get_megatron_global_info'))
57 |
58 | def init_megatron(self, default_megatron_kwargs: Optional[Dict] = None):
59 | # after super, we will call init of each worker
60 | if not self._is_init_with_detached_workers:
61 | # only init_megatron if the WorkerGroup is created from scratch
62 | self.execute_all_sync(method_name='init_megatron', default_megatron_kwargs=default_megatron_kwargs)
63 |
--------------------------------------------------------------------------------
/verl/single_controller/version/version:
--------------------------------------------------------------------------------
1 | 0.0.2
--------------------------------------------------------------------------------
/verl/third_party/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/third_party/vllm/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from importlib.metadata import version, PackageNotFoundError
16 |
17 |
18 | def get_version(pkg):
19 | try:
20 | return version(pkg)
21 | except PackageNotFoundError:
22 | return None
23 |
24 |
25 | package_name = 'vllm'
26 | package_version = get_version(package_name)
27 |
28 | if package_version == '0.3.1':
29 | vllm_version = '0.3.1'
30 | from .vllm_v_0_3_1.llm import LLM
31 | from .vllm_v_0_3_1.llm import LLMEngine
32 | from .vllm_v_0_3_1 import parallel_state
33 | elif package_version == '0.4.2':
34 | vllm_version = '0.4.2'
35 | from .vllm_v_0_4_2.llm import LLM
36 | from .vllm_v_0_4_2.llm import LLMEngine
37 | from .vllm_v_0_4_2 import parallel_state
38 | elif package_version == '0.5.4':
39 | vllm_version = '0.5.4'
40 | from .vllm_v_0_5_4.llm import LLM
41 | from .vllm_v_0_5_4.llm import LLMEngine
42 | from .vllm_v_0_5_4 import parallel_state
43 | elif package_version == '0.6.3':
44 | vllm_version = '0.6.3'
45 | from .vllm_v_0_6_3.llm import LLM
46 | from .vllm_v_0_6_3.llm import LLMEngine
47 | from .vllm_v_0_6_3 import parallel_state
48 | else:
49 | raise ValueError(
50 | f'vllm version {package_version} not supported. Currently supported versions are 0.3.1, 0.4.2, 0.5.4 and 0.6.3.'
51 | )
52 |
--------------------------------------------------------------------------------
/verl/third_party/vllm/vllm_v_0_3_1/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/third_party/vllm/vllm_v_0_3_1/tokenizer.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | # Copyright 2023 The vLLM team.
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | # Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/transformers_utils/tokenizer_group/tokenizer_group.py
15 |
16 | from typing import List, Optional, Tuple, Union
17 |
18 | from transformers import (AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast)
19 |
20 | from vllm.lora.request import LoRARequest
21 | from vllm.utils import make_async, LRUCache
22 | from vllm.transformers_utils.tokenizers import *
23 |
24 |
25 | class TokenizerGroup:
26 | """A group of tokenizers that can be used for LoRA adapters."""
27 |
28 | def __init__(self, tokenizer: PreTrainedTokenizer, enable_lora: bool, max_num_seqs: int,
29 | max_input_length: Optional[int]):
30 | self.enable_lora = enable_lora
31 | self.max_input_length = max_input_length
32 | self.tokenizer = tokenizer
33 | if enable_lora:
34 | self.lora_tokenizers = LRUCache(capacity=max_num_seqs)
35 | else:
36 | self.lora_tokenizers = None
37 |
38 | def encode(self,
39 | prompt: str,
40 | request_id: Optional[str] = None,
41 | lora_request: Optional[LoRARequest] = None) -> List[int]:
42 | tokenizer = self.get_lora_tokenizer(lora_request)
43 | return tokenizer.encode(prompt)
44 |
45 | async def encode_async(self,
46 | prompt: str,
47 | request_id: Optional[str] = None,
48 | lora_request: Optional[LoRARequest] = None) -> List[int]:
49 | tokenizer = await self.get_lora_tokenizer_async(lora_request)
50 | return tokenizer.encode(prompt)
51 |
52 | def get_lora_tokenizer(self, lora_request: Optional[LoRARequest]) -> "PreTrainedTokenizer":
53 | if not lora_request or not self.enable_lora:
54 | return self.tokenizer
55 | if lora_request.lora_int_id not in self.lora_tokenizers:
56 | # TODO(sgm): the lora tokenizer is also passed, but may be different
57 | tokenizer = self.tokenizer
58 | # tokenizer = (get_lora_tokenizer(
59 | # lora_request, **self.tokenizer_config) or self.tokenizer)
60 | self.lora_tokenizers.put(lora_request.lora_int_id, tokenizer)
61 | return tokenizer
62 | else:
63 | return self.lora_tokenizers.get(lora_request.lora_int_id)
64 |
65 | # FIXME(sgm): for simplicity, we assign the special token here
66 | @property
67 | def pad_token_id(self):
68 | return self.tokenizer.pad_token_id
69 |
70 | @property
71 | def eos_token_id(self):
72 | return self.tokenizer.eos_token_id
73 |
--------------------------------------------------------------------------------
/verl/third_party/vllm/vllm_v_0_4_2/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/third_party/vllm/vllm_v_0_4_2/hf_weight_loader.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | # Copyright 2023 The vLLM team.
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | # Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/models
15 |
16 | from typing import Dict, Union, Optional, Iterable, Tuple
17 |
18 | import torch
19 | import torch.nn as nn
20 |
21 | from vllm.model_executor.model_loader.utils import set_default_torch_dtype
22 | from vllm.model_executor.model_loader.weight_utils import default_weight_loader
23 |
24 |
25 | def update_hf_weight_loader():
26 | from vllm.model_executor.models.gemma import GemmaForCausalLM
27 | GemmaForCausalLM.load_weights = gemma_load_weights
28 |
29 |
30 | def gemma_load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
31 | stacked_params_mapping = [
32 | # (param_name, shard_name, shard_id)
33 | ("qkv_proj", "q_proj", "q"),
34 | ("qkv_proj", "k_proj", "k"),
35 | ("qkv_proj", "v_proj", "v"),
36 | ("gate_up_proj", "gate_proj", 0),
37 | ("gate_up_proj", "up_proj", 1),
38 | ]
39 | params_dict = dict(self.named_parameters())
40 | loaded_params = set()
41 | for name, loaded_weight in weights:
42 | for (param_name, shard_name, shard_id) in stacked_params_mapping:
43 | if shard_name not in name:
44 | continue
45 | name = name.replace(shard_name, param_name)
46 | # Skip loading extra bias for GPTQ models.
47 | if name.endswith(".bias") and name not in params_dict:
48 | continue
49 | param = params_dict[name]
50 | weight_loader = param.weight_loader
51 | weight_loader(param, loaded_weight, shard_id)
52 | break
53 | else:
54 | # lm_head is not used in vllm as it is tied with embed_token.
55 | # To prevent errors, skip loading lm_head.weight.
56 | if "lm_head.weight" in name:
57 | continue
58 | # Skip loading extra bias for GPTQ models.
59 | if name.endswith(".bias") and name not in params_dict:
60 | continue
61 | # GemmaRMSNorm is different from Llama's in that it multiplies
62 | # (1 + weight) to the output, instead of just weight.
63 | if "norm.weight" in name:
64 | norm_weight = loaded_weight + 1.0 # prevent inplace modify actor weights
65 | param = params_dict[name]
66 | weight_loader = getattr(param, "weight_loader", default_weight_loader)
67 | weight_loader(param, norm_weight)
68 | else:
69 | param = params_dict[name]
70 | weight_loader = getattr(param, "weight_loader", default_weight_loader)
71 | weight_loader(param, loaded_weight)
72 | loaded_params.add(name)
73 | unloaded_params = params_dict.keys() - loaded_params
74 | if unloaded_params:
75 | raise RuntimeError("Some weights are not initialized from checkpoints: "
76 | f"{unloaded_params}")
77 |
78 |
79 | def load_hf_weights(actor_weights: Dict, vllm_model: nn.Module):
80 | assert isinstance(actor_weights, Dict)
81 | with set_default_torch_dtype(next(vllm_model.parameters()).dtype): # TODO
82 | vllm_model.load_weights(actor_weights.items())
83 | for _, module in vllm_model.named_modules():
84 | quant_method = getattr(module, "quant_method", None)
85 | if quant_method is not None:
86 | quant_method.process_weights_after_loading(module)
87 | # FIXME: Remove this after Mixtral is updated
88 | # to use quant_method.
89 | if hasattr(module, "process_weights_after_loading"):
90 | module.process_weights_after_loading()
91 | vllm_model = vllm_model.cuda()
92 |
--------------------------------------------------------------------------------
/verl/third_party/vllm/vllm_v_0_4_2/tokenizer.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | # Copyright 2023 The vLLM team.
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | # Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/transformers_utils/tokenizer_group/tokenizer_group.py
15 |
16 | from typing import List, Optional, Tuple, Union
17 |
18 | from transformers import (AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast)
19 |
20 | from vllm.lora.request import LoRARequest
21 | from vllm.utils import make_async, LRUCache
22 | from vllm.transformers_utils.tokenizers import *
23 |
24 |
25 | class TokenizerGroup:
26 | """A group of tokenizers that can be used for LoRA adapters."""
27 |
28 | def __init__(self, tokenizer: PreTrainedTokenizer, enable_lora: bool, max_num_seqs: int,
29 | max_input_length: Optional[int]):
30 | self.enable_lora = enable_lora
31 | self.max_input_length = max_input_length
32 | self.tokenizer = tokenizer
33 | self.lora_tokenizers = LRUCache[PreTrainedTokenizer](capacity=max_num_seqs) if enable_lora else None
34 |
35 | def ping(self) -> bool:
36 | """Check if the tokenizer group is alive."""
37 | return True
38 |
39 | def get_max_input_len(self, lora_request: Optional[LoRARequest] = None) -> Optional[int]:
40 | """Get the maximum input length for the LoRA request."""
41 | return self.max_input_length
42 |
43 | def encode(self,
44 | prompt: str,
45 | request_id: Optional[str] = None,
46 | lora_request: Optional[LoRARequest] = None) -> List[int]:
47 | tokenizer = self.get_lora_tokenizer(lora_request)
48 | return tokenizer.encode(prompt)
49 |
50 | async def encode_async(self,
51 | prompt: str,
52 | request_id: Optional[str] = None,
53 | lora_request: Optional[LoRARequest] = None) -> List[int]:
54 | tokenizer = await self.get_lora_tokenizer_async(lora_request)
55 | return tokenizer.encode(prompt)
56 |
57 | def get_lora_tokenizer(self, lora_request: Optional[LoRARequest]) -> "PreTrainedTokenizer":
58 | if not lora_request or not self.enable_lora:
59 | return self.tokenizer
60 | if lora_request.lora_int_id not in self.lora_tokenizers:
61 | # TODO(sgm): the lora tokenizer is also passed, but may be different
62 | tokenizer = self.tokenizer
63 | # tokenizer = (get_lora_tokenizer(
64 | # lora_request, **self.tokenizer_config) or self.tokenizer)
65 | self.lora_tokenizers.put(lora_request.lora_int_id, tokenizer)
66 | return tokenizer
67 | else:
68 | return self.lora_tokenizers.get(lora_request.lora_int_id)
69 |
70 | # FIXME(sgm): for simplicity, we assign the special token here
71 | @property
72 | def pad_token_id(self):
73 | return self.tokenizer.pad_token_id
74 |
75 | @property
76 | def eos_token_id(self):
77 | return self.tokenizer.eos_token_id
78 |
--------------------------------------------------------------------------------
/verl/third_party/vllm/vllm_v_0_5_4/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/third_party/vllm/vllm_v_0_5_4/hf_weight_loader.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | # Copyright 2023 The vLLM team.
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | # Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/models
15 |
16 | from typing import Dict, Union, Optional, Iterable, Tuple
17 |
18 | import torch
19 | import torch.nn as nn
20 |
21 | from vllm.model_executor.model_loader.utils import set_default_torch_dtype
22 | from vllm.model_executor.model_loader.weight_utils import default_weight_loader
23 |
24 |
25 | def update_hf_weight_loader():
26 | print('no hf weight loader need to be updated')
27 | return
28 |
29 |
30 | def load_hf_weights(actor_weights: Dict, vllm_model: nn.Module):
31 | assert isinstance(actor_weights, Dict)
32 | with set_default_torch_dtype(next(vllm_model.parameters()).dtype): # TODO
33 | if vllm_model.config.tie_word_embeddings and "lm_head.weight" in actor_weights.keys():
34 | del actor_weights["lm_head.weight"]
35 | vllm_model.load_weights(actor_weights.items())
36 | for _, module in vllm_model.named_modules():
37 | quant_method = getattr(module, "quant_method", None)
38 | if quant_method is not None:
39 | quant_method.process_weights_after_loading(module)
40 | # FIXME: Remove this after Mixtral is updated
41 | # to use quant_method.
42 | if hasattr(module, "process_weights_after_loading"):
43 | module.process_weights_after_loading()
44 | vllm_model = vllm_model.cuda()
45 |
--------------------------------------------------------------------------------
/verl/third_party/vllm/vllm_v_0_5_4/tokenizer.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | # Copyright 2023 The vLLM team.
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | # Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/transformers_utils/tokenizer_group/tokenizer_group.py
15 |
16 | from typing import List, Optional, Tuple, Union
17 |
18 | from transformers import (AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast)
19 |
20 | from vllm.lora.request import LoRARequest
21 | from vllm.utils import make_async, LRUCache
22 | from vllm.transformers_utils.tokenizers import *
23 |
24 |
25 | class TokenizerGroup:
26 | """A group of tokenizers that can be used for LoRA adapters."""
27 |
28 | def __init__(self, tokenizer: PreTrainedTokenizer, enable_lora: bool, max_num_seqs: int,
29 | max_input_length: Optional[int]):
30 | self.enable_lora = enable_lora
31 | self.max_input_length = max_input_length
32 | self.tokenizer = tokenizer
33 | self.lora_tokenizers = LRUCache[PreTrainedTokenizer](capacity=max_num_seqs) if enable_lora else None
34 |
35 | def ping(self) -> bool:
36 | """Check if the tokenizer group is alive."""
37 | return True
38 |
39 | def get_max_input_len(self, lora_request: Optional[LoRARequest] = None) -> Optional[int]:
40 | """Get the maximum input length for the LoRA request."""
41 | return self.max_input_length
42 |
43 | def encode(self,
44 | prompt: str,
45 | request_id: Optional[str] = None,
46 | lora_request: Optional[LoRARequest] = None) -> List[int]:
47 | tokenizer = self.get_lora_tokenizer(lora_request)
48 | return tokenizer.encode(prompt)
49 |
50 | async def encode_async(self,
51 | prompt: str,
52 | request_id: Optional[str] = None,
53 | lora_request: Optional[LoRARequest] = None) -> List[int]:
54 | tokenizer = await self.get_lora_tokenizer_async(lora_request)
55 | return tokenizer.encode(prompt)
56 |
57 | def get_lora_tokenizer(self, lora_request: Optional[LoRARequest]) -> "PreTrainedTokenizer":
58 | if not lora_request or not self.enable_lora:
59 | return self.tokenizer
60 | if lora_request.lora_int_id not in self.lora_tokenizers:
61 | # TODO(sgm): the lora tokenizer is also passed, but may be different
62 | tokenizer = self.tokenizer
63 | # tokenizer = (get_lora_tokenizer(
64 | # lora_request, **self.tokenizer_config) or self.tokenizer)
65 | self.lora_tokenizers.put(lora_request.lora_int_id, tokenizer)
66 | return tokenizer
67 | else:
68 | return self.lora_tokenizers.get(lora_request.lora_int_id)
69 |
70 | # FIXME(sgm): for simplicity, we assign the special token here
71 | @property
72 | def pad_token_id(self):
73 | return self.tokenizer.pad_token_id
74 |
75 | @property
76 | def eos_token_id(self):
77 | return self.tokenizer.eos_token_id
78 |
--------------------------------------------------------------------------------
/verl/third_party/vllm/vllm_v_0_6_3/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/third_party/vllm/vllm_v_0_6_3/arg_utils.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | # Copyright 2023 The vLLM team.
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | # Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/engine/arg_utils.py
15 |
16 | import os
17 | from dataclasses import dataclass
18 |
19 | from transformers import PretrainedConfig
20 | from vllm.config import EngineConfig
21 | from vllm.engine.arg_utils import EngineArgs
22 |
23 | from .config import LoadConfig, ModelConfig
24 |
25 |
26 | @dataclass
27 | class EngineArgs(EngineArgs):
28 | model_hf_config: PretrainedConfig = None # for verl
29 |
30 | def __post_init__(self):
31 | pass
32 |
33 | def create_model_config(self) -> ModelConfig:
34 | return ModelConfig(
35 | hf_config=self.model_hf_config,
36 | tokenizer_mode=self.tokenizer_mode,
37 | trust_remote_code=self.trust_remote_code,
38 | dtype=self.dtype,
39 | seed=self.seed,
40 | revision=self.revision,
41 | code_revision=self.code_revision,
42 | rope_scaling=self.rope_scaling,
43 | rope_theta=self.rope_theta,
44 | tokenizer_revision=self.tokenizer_revision,
45 | max_model_len=self.max_model_len,
46 | quantization=self.quantization,
47 | quantization_param_path=self.quantization_param_path,
48 | enforce_eager=self.enforce_eager,
49 | max_context_len_to_capture=self.max_context_len_to_capture,
50 | max_seq_len_to_capture=self.max_seq_len_to_capture,
51 | max_logprobs=self.max_logprobs,
52 | disable_sliding_window=self.disable_sliding_window,
53 | skip_tokenizer_init=self.skip_tokenizer_init,
54 | served_model_name=self.served_model_name,
55 | limit_mm_per_prompt=self.limit_mm_per_prompt,
56 | use_async_output_proc=not self.disable_async_output_proc,
57 | override_neuron_config=self.override_neuron_config,
58 | config_format=self.config_format,
59 | mm_processor_kwargs=self.mm_processor_kwargs,
60 | )
61 |
62 | def create_load_config(self) -> LoadConfig:
63 | return LoadConfig(
64 | load_format=self.load_format,
65 | download_dir=self.download_dir,
66 | model_loader_extra_config=self.model_loader_extra_config,
67 | ignore_patterns=self.ignore_patterns,
68 | )
69 |
70 | def create_engine_config(self) -> EngineConfig:
71 | engine_config = super().create_engine_config()
72 |
73 | # NOTE[VERL]: Use the world_size set by torchrun
74 | world_size = int(os.getenv("WORLD_SIZE", "-1"))
75 | assert world_size != -1, "The world_size is set to -1, not initialized by TORCHRUN"
76 | engine_config.parallel_config.world_size = world_size
77 |
78 | return engine_config
79 |
--------------------------------------------------------------------------------
/verl/third_party/vllm/vllm_v_0_6_3/hf_weight_loader.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | # Copyright 2023 The vLLM team.
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | # Adapted from https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/model_loader
15 |
16 | from typing import Dict
17 |
18 | import torch.nn as nn
19 | from vllm.model_executor.model_loader.utils import set_default_torch_dtype
20 |
21 |
22 | def update_hf_weight_loader():
23 | print("no hf weight loader need to be updated")
24 | return
25 |
26 |
27 | def load_hf_weights(actor_weights: Dict, vllm_model: nn.Module):
28 | assert isinstance(actor_weights, Dict)
29 | with set_default_torch_dtype(next(vllm_model.parameters()).dtype): # TODO
30 | if vllm_model.config.tie_word_embeddings and "lm_head.weight" in actor_weights.keys():
31 | del actor_weights["lm_head.weight"]
32 | vllm_model.load_weights(actor_weights.items())
33 | for _, module in vllm_model.named_modules():
34 | quant_method = getattr(module, "quant_method", None)
35 | if quant_method is not None:
36 | quant_method.process_weights_after_loading(module)
37 | # FIXME: Remove this after Mixtral is updated
38 | # to use quant_method.
39 | if hasattr(module, "process_weights_after_loading"):
40 | module.process_weights_after_loading()
41 | vllm_model = vllm_model.cuda()
42 |
--------------------------------------------------------------------------------
/verl/third_party/vllm/vllm_v_0_6_3/tokenizer.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | # Copyright 2023 The vLLM team.
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | # Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/transformers_utils/tokenizer_group/tokenizer_group.py
15 |
16 | from typing import Optional
17 |
18 | from transformers import PreTrainedTokenizer
19 | from vllm.transformers_utils.tokenizer_group import TokenizerGroup
20 | from vllm.utils import LRUCache
21 |
22 |
23 | class TokenizerGroup(TokenizerGroup):
24 | """A group of tokenizers that can be used for LoRA adapters."""
25 |
26 | def __init__(self, tokenizer: PreTrainedTokenizer, enable_lora: bool, max_num_seqs: int,
27 | max_input_length: Optional[int]):
28 | self.enable_lora = enable_lora
29 | self.max_input_length = max_input_length
30 | self.tokenizer = tokenizer
31 | self.lora_tokenizers = LRUCache[PreTrainedTokenizer](capacity=max_num_seqs) if enable_lora else None
32 |
33 | # FIXME(sgm): for simplicity, we assign the special token here
34 | @property
35 | def pad_token_id(self):
36 | return self.tokenizer.pad_token_id
37 |
38 | @property
39 | def eos_token_id(self):
40 | return self.tokenizer.eos_token_id
41 |
--------------------------------------------------------------------------------
/verl/trainer/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/trainer/config/evaluation.yaml:
--------------------------------------------------------------------------------
1 | data:
2 | path: /tmp/math_Qwen2-7B-Instruct.parquet
3 | prompt_key: prompt
4 | response_key: responses
5 | data_source_key: data_source
6 | reward_model_key: reward_model
--------------------------------------------------------------------------------
/verl/trainer/config/generation.yaml:
--------------------------------------------------------------------------------
1 | trainer:
2 | nnodes: 1
3 | n_gpus_per_node: 8
4 |
5 | data:
6 | path: ~/data/rlhf/math/test.parquet
7 | prompt_key: prompt
8 | n_samples: 5
9 | output_path: /opt/tiger/math_Qwen2-7B-Instruct.parquet
10 | batch_size: 128
11 |
12 | model:
13 | path: ~/models/Qwen2-7B-Instruct
14 | external_lib: null
15 | rollout:
16 | name: vllm
17 | temperature: 1.0
18 | top_k: 50 # 0 for hf rollout, -1 for vllm rollout
19 | top_p: 0.7
20 | prompt_length: 1536
21 | response_length: 512
22 | # for vllm rollout
23 | dtype: bfloat16 # should align with FSDP
24 | gpu_memory_utilization: 0.5
25 | ignore_eos: False
26 | micro_batch_size: 256
27 | enforce_eager: True
28 | free_cache_engine: True
29 | load_format: dummy_dtensor
30 | tensor_model_parallel_size: 1
31 | max_num_batched_tokens: 8192
32 | max_num_seqs: 1024
33 | log_prob_micro_batch_size: 8
34 | # for hf rollout
35 | do_sample: True
--------------------------------------------------------------------------------
/verl/trainer/config/sft_trainer.yaml:
--------------------------------------------------------------------------------
1 | data:
2 | train_batch_size: 256
3 | micro_batch_size: 16 # this is also val batch size
4 | train_files: ~/data/gsm8k/train.parquet
5 | val_files: ~/data/gsm8k/test.parquet
6 | prompt_key: question
7 | response_key: answer
8 | max_length: 1024
9 | truncation: error
10 | balance_dp_token: False
11 | chat_template: null
12 | model:
13 | partial_pretrain: ~/models/gemma-1.1-7b-it
14 | fsdp_config:
15 | wrap_policy:
16 | min_num_params: 0
17 | cpu_offload: False
18 | offload_params: False
19 | external_lib: null
20 | enable_gradient_checkpointing: False
21 | trust_remote_code: False
22 | lora_rank: 0 # Set to positive value to enable LoRA (e.g., 32)
23 | lora_alpha: 16 # LoRA scaling factor
24 | target_modules: [q_proj, v_proj] # Target modules for LoRA adaptation
25 | optim:
26 | lr: 1e-5
27 | betas: [0.9, 0.95]
28 | weight_decay: 0.01
29 | warmup_steps_ratio: 0.1
30 | clip_grad: 1.0
31 |
32 | trainer:
33 | default_local_dir: /tmp/sft_model
34 | default_hdfs_dir: hdfs://tmp/experiments/gsm8k/gemma-1.1-7b-it/ # change the hdfs path here
35 | resume_path: null
36 | project_name: gsm8k-sft
37 | experiment_name: test
38 | total_epochs: 4
39 | total_training_steps: null
40 | validate_before_training: False
41 | logger: ['console']
42 | seed: 1
43 |
--------------------------------------------------------------------------------
/verl/trainer/main_eval.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | Offline evaluate the performance of a generated file using reward model and ground truth verifier.
16 | The input is a parquet file that contains N generated sequences and (optional) the ground truth.
17 |
18 | """
19 |
20 | import hydra
21 | from verl.utils.fs import copy_local_path_from_hdfs
22 | from verl.utils.reward_score import math, gsm8k
23 | import pandas as pd
24 | import numpy as np
25 |
26 |
27 | def select_reward_fn(data_source):
28 | if data_source == 'lighteval/MATH':
29 | return math.compute_score
30 | else:
31 | raise NotImplementedError
32 |
33 |
34 | @hydra.main(config_path='config', config_name='evaluation', version_base=None)
35 | def main(config):
36 | local_path = copy_local_path_from_hdfs(config.data.path)
37 | dataset = pd.read_parquet(local_path)
38 | prompts = dataset[config.data.prompt_key]
39 | responses = dataset[config.data.response_key]
40 | data_sources = dataset[config.data.data_source_key]
41 | reward_model_data = dataset[config.data.reward_model_key]
42 |
43 | passes = 0
44 |
45 | total = len(dataset)
46 |
47 | for i in range(total):
48 | response_lst = responses[i]
49 | data_source = data_sources[i]
50 | # select reward score based on data_source
51 | prompt = prompts[i]
52 | reward_data = reward_model_data[i]
53 | reward_fn = select_reward_fn(data_source)
54 | ground_truth = reward_data['ground_truth']
55 | score_lst = []
56 | for r in response_lst:
57 | score = reward_fn(r, ground_truth)
58 | score_lst.append(score)
59 |
60 | max_score = np.max(score_lst)
61 |
62 | if max_score == 1:
63 | passes += 1
64 |
65 | print(f'pass@5: {passes / total}')
66 |
67 |
68 | if __name__ == '__main__':
69 | main()
70 |
--------------------------------------------------------------------------------
/verl/trainer/ppo/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/trainer/runtime_env.yaml:
--------------------------------------------------------------------------------
1 | working_dir: ./
2 | excludes: ["/.git/"]
3 | env_vars:
4 | TORCH_NCCL_AVOID_RECORD_STREAMS: "1"
5 | VLLM_ATTENTION_BACKEND: "XFORMERS"
--------------------------------------------------------------------------------
/verl/utils/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from . import tokenizer
16 | from .tokenizer import *
17 |
18 | __all__ = tokenizer.__all__
--------------------------------------------------------------------------------
/verl/utils/config.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from typing import Dict
16 |
17 | from omegaconf import DictConfig
18 |
19 |
20 | def update_dict_with_config(dictionary: Dict, config: DictConfig):
21 | for key in dictionary:
22 | if hasattr(config, key):
23 | dictionary[key] = getattr(config, key)
24 |
--------------------------------------------------------------------------------
/verl/utils/dataset/README.md:
--------------------------------------------------------------------------------
1 | # Dataset Format
2 | ## RLHF dataset
3 | We 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.
4 |
5 | Math problems
6 | ```json
7 | {
8 | "data_source": "openai/gsm8k",
9 | "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 \"####\""}],
10 | "ability": "math",
11 | "reward_model": {
12 | "style": "rule",
13 | "ground_truth": ["72"]
14 | },
15 | }
16 | ```
17 |
--------------------------------------------------------------------------------
/verl/utils/dataset/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from .rl_dataset import RLHFDataset
16 | from .rm_dataset import RMDataset
--------------------------------------------------------------------------------
/verl/utils/debug/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from .performance import log_gpu_memory_usage
--------------------------------------------------------------------------------
/verl/utils/debug/performance.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | import torch
16 | import torch.distributed as dist
17 | import logging
18 |
19 |
20 | def log_gpu_memory_usage(head: str, logger: logging.Logger = None, level=logging.DEBUG, rank: int = 0):
21 | if (not dist.is_initialized()) or (rank is None) or (dist.get_rank() == rank):
22 | memory_allocated = torch.cuda.memory_allocated() / 1024**3
23 | memory_reserved = torch.cuda.memory_reserved() / 1024**3
24 |
25 | message = f'{head}, memory allocated (GB): {memory_allocated}, memory reserved (GB): {memory_reserved}'
26 |
27 | if logger is None:
28 | print(message)
29 | else:
30 | logger.log(msg=message, level=level)
31 |
--------------------------------------------------------------------------------
/verl/utils/debug/trajectory_tracker.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | Trajectory tracker can be inserted into code to save the intermediate results.
16 | The results will be dump to hdfs for offline comparison.
17 | Each process will have a client that first move all the tensors to CPU
18 | """
19 |
20 | from verl.utils.hdfs_io import makedirs, copy
21 | import torch
22 | import os
23 | import ray
24 | import io
25 | import tempfile
26 |
27 | from collections import deque
28 |
29 | remote_copy = ray.remote(copy)
30 |
31 |
32 | @ray.remote
33 | def save_to_hdfs(data: io.BytesIO, name, hdfs_dir, verbose):
34 | filename = name + '.pth'
35 | with tempfile.TemporaryDirectory() as tmpdirname:
36 | local_filepath = os.path.join(tmpdirname, filename)
37 | with open(local_filepath, 'wb') as f:
38 | f.write(data.getbuffer())
39 | # upload to hdfs
40 |
41 | if verbose:
42 | print(f'Saving {local_filepath} to {hdfs_dir}')
43 | try:
44 | copy(local_filepath, hdfs_dir)
45 | except Exception as e:
46 | print(e)
47 |
48 |
49 | @ray.remote
50 | class TrajectoryTracker():
51 |
52 | def __init__(self, hdfs_dir, verbose) -> None:
53 | self.hdfs_dir = hdfs_dir
54 | makedirs(hdfs_dir)
55 | self.verbose = verbose
56 |
57 | self.handle = deque()
58 |
59 | def dump(self, data: io.BytesIO, name):
60 | # get a temp file and write to it
61 | self.handle.append(save_to_hdfs.remote(data, name, self.hdfs_dir, self.verbose))
62 |
63 | def wait_for_hdfs(self):
64 | while len(self.handle) != 0:
65 | future = self.handle.popleft()
66 | ray.get(future)
67 |
68 |
69 | def dump_data(data, name):
70 | enable = os.getenv('VERL_ENABLE_TRACKER', '0') == '1'
71 | if not enable:
72 | return
73 | buffer = io.BytesIO()
74 | torch.save(data, buffer)
75 | tracker = get_trajectory_tracker()
76 | ray.get(tracker.dump.remote(buffer, name))
77 |
78 |
79 | def get_trajectory_tracker():
80 | hdfs_dir = os.getenv('VERL_TRACKER_HDFS_DIR', default=None)
81 | verbose = os.getenv('VERL_TRACKER_VERBOSE', default='0') == '1'
82 | assert hdfs_dir is not None
83 | tracker = TrajectoryTracker.options(name="global_tracker", get_if_exists=True,
84 | lifetime="detached").remote(hdfs_dir, verbose)
85 | return tracker
86 |
87 |
88 | if __name__ == '__main__':
89 | # testing
90 | os.environ['VERL_ENABLE_TRACKER'] = '1'
91 | os.environ['VERL_TRACKER_HDFS_DIR'] = '~/debug/test'
92 |
93 | @ray.remote
94 | def process(iter):
95 | data = {'obs': torch.randn(10, 20)}
96 | dump_data(data, f'process_{iter}_obs')
97 |
98 | ray.init()
99 |
100 | output_lst = []
101 |
102 | for i in range(10):
103 | output_lst.append(process.remote(i))
104 |
105 | out = ray.get(output_lst)
106 |
107 | tracker = get_trajectory_tracker()
108 | ray.get(tracker.wait_for_hdfs.remote())
109 |
--------------------------------------------------------------------------------
/verl/utils/distributed.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """Utilities for distributed training."""
15 | import os
16 |
17 |
18 | def initialize_global_process_group(timeout_second=36000):
19 | import torch.distributed
20 | from datetime import timedelta
21 | torch.distributed.init_process_group('nccl', timeout=timedelta(seconds=timeout_second))
22 | local_rank = int(os.environ["LOCAL_RANK"])
23 | rank = int(os.environ["RANK"])
24 | world_size = int(os.environ["WORLD_SIZE"])
25 |
26 | if torch.distributed.is_initialized():
27 | torch.cuda.set_device(local_rank)
28 | return local_rank, rank, world_size
29 |
--------------------------------------------------------------------------------
/verl/utils/fs.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | # -*- coding: utf-8 -*-
17 | """File-system agnostic IO APIs"""
18 | import os
19 | import tempfile
20 | import hashlib
21 |
22 | from .hdfs_io import copy, makedirs, exists
23 |
24 | __all__ = ["copy", "exists", "makedirs"]
25 |
26 | _HDFS_PREFIX = "hdfs://"
27 |
28 |
29 | def _is_non_local(path):
30 | return path.startswith(_HDFS_PREFIX)
31 |
32 |
33 | def md5_encode(path: str) -> str:
34 | return hashlib.md5(path.encode()).hexdigest()
35 |
36 |
37 | def get_local_temp_path(hdfs_path: str, cache_dir: str) -> str:
38 | """Return a local temp path that joins cache_dir and basename of hdfs_path
39 |
40 | Args:
41 | hdfs_path:
42 | cache_dir:
43 |
44 | Returns:
45 |
46 | """
47 | # make a base64 encoding of hdfs_path to avoid directory conflict
48 | encoded_hdfs_path = md5_encode(hdfs_path)
49 | temp_dir = os.path.join(cache_dir, encoded_hdfs_path)
50 | os.makedirs(temp_dir, exist_ok=True)
51 | dst = os.path.join(temp_dir, os.path.basename(hdfs_path))
52 | return dst
53 |
54 |
55 | def copy_local_path_from_hdfs(src: str, cache_dir=None, filelock='.file.lock', verbose=False) -> str:
56 | """Copy src from hdfs to local if src is on hdfs or directly return src.
57 | If cache_dir is None, we will use the default cache dir of the system. Note that this may cause conflicts if
58 | the src name is the same between calls
59 |
60 | Args:
61 | src (str): a HDFS path of a local path
62 |
63 | Returns:
64 | a local path of the copied file
65 | """
66 | from filelock import FileLock
67 |
68 | assert src[-1] != '/', f'Make sure the last char in src is not / because it will cause error. Got {src}'
69 |
70 | if _is_non_local(src):
71 | # download from hdfs to local
72 | if cache_dir is None:
73 | # get a temp folder
74 | cache_dir = tempfile.gettempdir()
75 | os.makedirs(cache_dir, exist_ok=True)
76 | assert os.path.exists(cache_dir)
77 | local_path = get_local_temp_path(src, cache_dir)
78 | # get a specific lock
79 | filelock = md5_encode(src) + '.lock'
80 | lock_file = os.path.join(cache_dir, filelock)
81 | with FileLock(lock_file=lock_file):
82 | if not os.path.exists(local_path):
83 | if verbose:
84 | print(f'Copy from {src} to {local_path}')
85 | copy(src, local_path)
86 | return local_path
87 | else:
88 | return src
89 |
--------------------------------------------------------------------------------
/verl/utils/import_utils.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | Utilities to check if packages are available.
16 | We assume package availability won't change during runtime.
17 | """
18 |
19 | from functools import cache
20 | from typing import List
21 |
22 |
23 | @cache
24 | def is_megatron_core_available():
25 | try:
26 | from megatron.core import parallel_state as mpu
27 | return True
28 | except ImportError:
29 | return False
30 |
31 |
32 | @cache
33 | def is_vllm_available():
34 | try:
35 | import vllm
36 | return True
37 | except ImportError:
38 | return False
39 |
40 |
41 | def import_external_libs(external_libs=None):
42 | if external_libs is None:
43 | return
44 | if not isinstance(external_libs, List):
45 | external_libs = [external_libs]
46 | import importlib
47 | for external_lib in external_libs:
48 | importlib.import_module(external_lib)
49 |
--------------------------------------------------------------------------------
/verl/utils/logger/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/utils/logger/aggregate_logger.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | A Ray logger will receive logging info from different processes.
16 | """
17 | import numbers
18 | from typing import Dict
19 |
20 |
21 | def concat_dict_to_str(dict: Dict, step):
22 | output = [f'step:{step}']
23 | for k, v in dict.items():
24 | if isinstance(v, numbers.Number):
25 | output.append(f'{k}:{v:.3f}')
26 | output_str = ' - '.join(output)
27 | return output_str
28 |
29 |
30 | class LocalLogger:
31 |
32 | def __init__(self, remote_logger=None, enable_wandb=False, print_to_console=False):
33 | self.print_to_console = print_to_console
34 | if print_to_console:
35 | print('Using LocalLogger is deprecated. The constructor API will change ')
36 |
37 | def flush(self):
38 | pass
39 |
40 | def log(self, data, step):
41 | if self.print_to_console:
42 | print(concat_dict_to_str(data, step=step), flush=True)
--------------------------------------------------------------------------------
/verl/utils/logging_utils.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | import logging
16 |
17 |
18 | def set_basic_config(level):
19 | """
20 | This function sets the global logging format and level. It will be called when import verl
21 | """
22 | logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s', level=level)
23 |
--------------------------------------------------------------------------------
/verl/utils/megatron/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/utils/megatron/memory.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | import torch
16 |
17 |
18 | class MemoryBuffer:
19 |
20 | def __init__(self, numel, numel_padded, dtype):
21 | self.numel = numel
22 | self.numel_padded = numel_padded
23 | self.dtype = dtype
24 | self.data = torch.zeros(self.numel_padded,
25 | dtype=self.dtype,
26 | device=torch.cuda.current_device(),
27 | requires_grad=False)
28 |
29 | def zero(self):
30 | """Reset the buffer to zero."""
31 | self.data.zero_()
32 |
33 | def get(self, shape, start_index):
34 | """Return a tensor with the input `shape` as a view into the
35 | 1-D data starting at `start_index`."""
36 | end_index = start_index + shape.numel()
37 | assert end_index <= self.numel, \
38 | 'requested tensor is out of the buffer range.'
39 | buffer_tensor = self.data[start_index:end_index]
40 | buffer_tensor = buffer_tensor.view(shape)
41 | return buffer_tensor
42 |
--------------------------------------------------------------------------------
/verl/utils/megatron/pipeline_parallel.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | import torch
17 | from megatron.core import parallel_state as mpu
18 |
19 | from .sequence_parallel import pad_to_sequence_parallel
20 |
21 |
22 | def compute_transformers_input_shapes(batches, meta_info):
23 | from flash_attn.bert_padding import unpad_input # flash 2 is a must for Megatron
24 | # pre-compute input shapes for each micro-batch at each pp stage
25 | input_shapes = []
26 | for model_inputs in batches:
27 | input_ids = model_inputs['input_ids']
28 | attention_mask = model_inputs['attention_mask']
29 | input_ids_rmpad = unpad_input(input_ids.unsqueeze(dim=-1), attention_mask)[0] # (total_nnz, 1)
30 | if meta_info['sequence_parallel']:
31 | input_ids_rmpad = pad_to_sequence_parallel(input_ids_rmpad)
32 | # compute shapes for model_inputs
33 | input_shapes.append(
34 | torch.Size([
35 | input_ids_rmpad.shape[0] // mpu.get_tensor_model_parallel_world_size(), 1, meta_info['hidden_size']
36 | ]))
37 | else:
38 | # compute shapes for model_inputs
39 | input_shapes.append(torch.Size([input_ids_rmpad.shape[0], 1, meta_info['hidden_size']]))
40 | return input_shapes
41 |
42 |
43 | def make_batch_generator(batches, vpp_size):
44 | if vpp_size > 1:
45 | # has vpp
46 | batch_generator = [batches] * vpp_size # number of vpp chunks
47 | batch_generator = [iter(b) for b in batch_generator]
48 | else:
49 | # no vpp
50 | batch_generator = iter(batches)
51 | return batch_generator
52 |
--------------------------------------------------------------------------------
/verl/utils/megatron/sequence_parallel.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 |
16 | import torch
17 | import torch.nn.functional as F
18 | from megatron.core import parallel_state as mpu
19 |
20 |
21 | def mark_parameter_as_sequence_parallel(parameter):
22 | setattr(parameter, 'sequence_parallel', True)
23 |
24 |
25 | def is_sequence_parallel_param(param):
26 | return hasattr(param, 'sequence_parallel') and param.sequence_parallel
27 |
28 |
29 | def pad_to_sequence_parallel(unpad_tokens: torch.Tensor):
30 | """pad the tokens such that the total length is a multiple of sp world size
31 |
32 | Args:
33 | unpad_tokens: (total_nnz, ...). Tokens after removing padding
34 |
35 | Returns:
36 |
37 | """
38 | total_nnz = unpad_tokens.shape[0]
39 | sp_world_size = mpu.get_tensor_model_parallel_world_size()
40 |
41 | if total_nnz % sp_world_size == 0:
42 | pad_size = 0
43 | else:
44 | pad_size = sp_world_size - total_nnz % sp_world_size
45 |
46 | if pad_size > 0:
47 | if unpad_tokens.ndim == 1:
48 | unpad_tokens = F.pad(unpad_tokens, (0, pad_size))
49 | elif unpad_tokens.ndim == 2:
50 | unpad_tokens = F.pad(unpad_tokens, (0, 0, 0, pad_size))
51 | else:
52 | raise NotImplementedError(f'Padding dim {unpad_tokens.ndim()} is not supported')
53 |
54 | return unpad_tokens
55 |
--------------------------------------------------------------------------------
/verl/utils/py_functional.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | Contain small python utility functions
16 | """
17 |
18 | from typing import Dict
19 | from types import SimpleNamespace
20 |
21 |
22 | def union_two_dict(dict1: Dict, dict2: Dict):
23 | """Union two dict. Will throw an error if there is an item not the same object with the same key.
24 |
25 | Args:
26 | dict1:
27 | dict2:
28 |
29 | Returns:
30 |
31 | """
32 | for key, val in dict2.items():
33 | if key in dict1:
34 | assert dict2[key] == dict1[key], \
35 | f'{key} in meta_dict1 and meta_dict2 are not the same object'
36 | dict1[key] = val
37 |
38 | return dict1
39 |
40 |
41 | def append_to_dict(data: Dict, new_data: Dict):
42 | for key, val in new_data.items():
43 | if key not in data:
44 | data[key] = []
45 | data[key].append(val)
46 |
47 |
48 | class NestedNamespace(SimpleNamespace):
49 |
50 | def __init__(self, dictionary, **kwargs):
51 | super().__init__(**kwargs)
52 | for key, value in dictionary.items():
53 | if isinstance(value, dict):
54 | self.__setattr__(key, NestedNamespace(value))
55 | else:
56 | self.__setattr__(key, value)
57 |
--------------------------------------------------------------------------------
/verl/utils/ray_utils.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | Contains commonly used utilities for ray
16 | """
17 |
18 | import ray
19 |
20 | import concurrent.futures
21 |
22 |
23 | def parallel_put(data_list, max_workers=None):
24 |
25 | def put_data(index, data):
26 | return index, ray.put(data)
27 |
28 | if max_workers is None:
29 | max_workers = min(len(data_list), 16)
30 |
31 | with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
32 | data_list_f = [executor.submit(put_data, i, data) for i, data in enumerate(data_list)]
33 | res_lst = []
34 | for future in concurrent.futures.as_completed(data_list_f):
35 | res_lst.append(future.result())
36 |
37 | # reorder based on index
38 | output = [None for _ in range(len(data_list))]
39 | for res in res_lst:
40 | index, data_ref = res
41 | output[index] = data_ref
42 |
43 | return output
44 |
--------------------------------------------------------------------------------
/verl/utils/rendezvous/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/utils/rendezvous/ray_backend.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | import logging
16 | import time
17 |
18 | from cupy.cuda.nccl import NcclCommunicator, get_unique_id
19 |
20 | import ray
21 | from ray.util import list_named_actors
22 |
23 |
24 | @ray.remote
25 | class NCCLIDStore:
26 |
27 | def __init__(self, nccl_id):
28 | self._nccl_id = nccl_id
29 |
30 | def get(self):
31 | return self._nccl_id
32 |
33 |
34 | def get_nccl_id_store_by_name(name):
35 | all_actors = list_named_actors(all_namespaces=True)
36 | matched_actors = [actor for actor in all_actors if actor.get("name", None) == name]
37 | if len(matched_actors) == 1:
38 | actor = matched_actors[0]
39 | return ray.get_actor(**actor)
40 | elif len(matched_actors) > 1:
41 | logging.warning(f"multiple actors with same name found: {matched_actors}")
42 | elif len(matched_actors) == 0:
43 | logging.info(f"failed to get any actor named {name}")
44 | return None
45 |
46 |
47 | def create_nccl_communicator_in_ray(rank: int,
48 | world_size: int,
49 | group_name: str,
50 | max_retries: int = 100,
51 | interval_s: int = 5):
52 | if rank == 0:
53 | nccl_id = get_unique_id()
54 | nccl_id_store = NCCLIDStore.options(name=group_name).remote(nccl_id)
55 |
56 | assert ray.get(nccl_id_store.get.remote()) == nccl_id
57 | communicator = NcclCommunicator(
58 | ndev=world_size,
59 | commId=nccl_id,
60 | rank=0,
61 | )
62 | return communicator
63 | else:
64 | for i in range(max_retries):
65 | nccl_id_store = get_nccl_id_store_by_name(group_name)
66 | if nccl_id_store is not None:
67 | logging.info(f"nccl_id_store {group_name} got")
68 | nccl_id = ray.get(nccl_id_store.get.remote())
69 | logging.info(f"nccl id for {group_name} got: {nccl_id}")
70 | communicator = NcclCommunicator(
71 | ndev=world_size,
72 | commId=nccl_id,
73 | rank=rank,
74 | )
75 | return communicator
76 | logging.info(f"failed to get nccl_id for {i+1} time, sleep for {interval_s} seconds")
77 | time.sleep(interval_s)
78 |
--------------------------------------------------------------------------------
/verl/utils/reward_score/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/utils/reward_score/countdown.py:
--------------------------------------------------------------------------------
1 | import re
2 | import random
3 | import ast
4 | import operator
5 |
6 |
7 | def extract_solution(solution_str):
8 | """Extract the equation from the solution string."""
9 | # Remove everything before the first "Assistant:"
10 | if "Assistant:" in solution_str:
11 | solution_str = solution_str.split("Assistant:", 1)[1]
12 | elif "<|im_start|>assistant" in solution_str:
13 | solution_str = solution_str.split("<|im_start|>assistant", 1)[1]
14 | else:
15 | return None
16 | solution_str = solution_str.split('\n')[-1]
17 |
18 | answer_pattern = r'(.*?)'
19 | match = re.finditer(answer_pattern, solution_str)
20 | matches = list(match)
21 | if matches:
22 | final_answer = matches[-1].group(1).strip()
23 | else:
24 | final_answer = None
25 | return final_answer
26 |
27 |
28 | def validate_equation(equation_str, available_numbers):
29 | """Validate that equation only uses available numbers and each number once."""
30 | try:
31 | # Extract all numbers from the equation
32 | numbers_in_eq = [int(n) for n in re.findall(r'\d+', equation_str)]
33 |
34 | # Check if all numbers in equation are available
35 | available_numbers = sorted(available_numbers)
36 | numbers_in_eq = sorted(numbers_in_eq)
37 |
38 | # Each number should be used exactly once
39 | return numbers_in_eq == available_numbers
40 | except:
41 | return False
42 |
43 |
44 | def evaluate_equation(equation_str):
45 | """Safely evaluate the arithmetic equation using eval() with precautions."""
46 | try:
47 | # Define a regex pattern that only allows numbers, operators, parentheses, and whitespace
48 | allowed_pattern = r'^[\d+\-*/().\s]+$'
49 | if not re.match(allowed_pattern, equation_str):
50 | raise ValueError("Invalid characters in equation.")
51 |
52 | # Evaluate the equation with restricted globals and locals
53 | result = eval(equation_str, {"__builtins__": None}, {})
54 | return result
55 | except Exception as e:
56 | return None
57 |
58 |
59 | def compute_score(solution_str, ground_truth, method='strict', format_score=0.1, score=1.):
60 | """The scoring function for countdown task.
61 |
62 | Args:
63 | solution_str: the solution text
64 | ground_truth: dictionary containing target number and available numbers
65 | method: the method to extract the solution
66 | format_score: the score for correct format but wrong answer
67 | score: the score for the correct answer
68 | """
69 | target = ground_truth['target']
70 | numbers = ground_truth['numbers']
71 |
72 | equation = extract_solution(solution_str=solution_str)
73 | do_print = random.randint(1, 64) == 1
74 |
75 | if do_print:
76 | print(f"--------------------------------")
77 | print(f"Target: {target} | Numbers: {numbers}")
78 | print(f"Extracted equation: {equation}")
79 | print(f"Solution string: {solution_str}")
80 |
81 | if equation is None:
82 | if do_print:
83 | print(f"No equation found")
84 | return 0
85 |
86 | # Validate equation uses correct numbers
87 | if not validate_equation(equation, numbers):
88 | if do_print:
89 | print(f"Invalid equation")
90 | return format_score
91 |
92 | # Evaluate equation
93 | try:
94 | result = evaluate_equation(equation)
95 | if result is None:
96 | if do_print:
97 | print(f"Could not evaluate equation")
98 | return format_score
99 |
100 | if abs(result - target) < 1e-5: # Account for floating point precision
101 | if do_print:
102 | print(f"Correct equation: {equation} = {result}")
103 | return score
104 | else:
105 | if do_print:
106 | print(f"Wrong result: equation = {result}, target = {target}")
107 | return format_score
108 | except:
109 | if do_print:
110 | print(f"Error evaluating equation")
111 | return format_score
--------------------------------------------------------------------------------
/verl/utils/reward_score/gsm8k.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | import re
16 |
17 |
18 | def extract_solution(solution_str, method='strict'):
19 | assert method in ['strict', 'flexible']
20 |
21 | if method == 'strict':
22 | # this also tests the formatting of the model
23 | solution = re.search("#### (\\-?[0-9\\.\\,]+)", solution_str)
24 | if solution is None:
25 | final_answer = None
26 | else:
27 | final_answer = solution.group(0)
28 | final_answer = final_answer.split('#### ')[1].replace(',', '').replace('$', '')
29 | elif method == 'flexible':
30 | answer = re.findall("(\\-?[0-9\\.\\,]+)", solution_str)
31 | final_answer = None
32 | if len(answer) == 0:
33 | # no reward is there is no answer
34 | pass
35 | else:
36 | invalid_str = ['', '.']
37 | # find the last number that is not '.'
38 | for final_answer in reversed(answer):
39 | if final_answer not in invalid_str:
40 | break
41 | return final_answer
42 |
43 |
44 | def compute_score(solution_str, ground_truth, method='strict', format_score=0., score=1.):
45 | """The scoring function for GSM8k.
46 |
47 | 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.
48 |
49 | Args:
50 | solution_str: the solution text
51 | ground_truth: the ground truth
52 | method: the method to extract the solution, choices are 'strict' and 'flexible'
53 | format_score: the score for the format
54 | score: the score for the correct answer
55 | """
56 | answer = extract_solution(solution_str=solution_str, method=method)
57 | if answer is None:
58 | return 0
59 | else:
60 | if answer == ground_truth:
61 | return score
62 | else:
63 | return format_score
--------------------------------------------------------------------------------
/verl/utils/reward_score/multiply.py:
--------------------------------------------------------------------------------
1 | import re
2 | import random
3 |
4 |
5 | def extract_solution(solution_str):
6 | # Remove everything before the first "Assistant:"
7 | if "Assistant:" in solution_str:
8 | solution_str = solution_str.split("Assistant:", 1)[1]
9 | else:
10 | return None
11 |
12 | answer_pattern = r'(.*?)'
13 | match = re.finditer(answer_pattern, solution_str)
14 | matches = list(match)
15 | if matches:
16 | final_answer = matches[-1].group(1).strip()
17 | else:
18 | final_answer = None
19 | if final_answer is not None:
20 | try:
21 | int_final_answer = int(final_answer)
22 | except ValueError:
23 | final_answer = None
24 | return final_answer
25 |
26 |
27 | def compute_score(solution_str, ground_truth, method='strict', format_score=0.1, score=1.):
28 | """The scoring function for GSM8k.
29 |
30 | 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.
31 |
32 | Args:
33 | solution_str: the solution text
34 | ground_truth: the ground truth
35 | method: the method to extract the solution, choices are 'strict' and 'flexible'
36 | format_score: the score for the format
37 | score: the score for the correct answer
38 | """
39 | answer = extract_solution(solution_str=solution_str)
40 | do_print = random.randint(1, 64) == 1
41 | if do_print:
42 | print(f"--------------------------------")
43 | print(f"Ground truth: {ground_truth} | Extracted answer: {answer}")
44 | print(f"Solution string: {solution_str}")
45 |
46 | if answer is None:
47 | if do_print:
48 | print(f"No answer found")
49 | return 0
50 | else:
51 | if int(answer) == int(ground_truth):
52 | if do_print:
53 | print(f"Correct answer: {answer}")
54 | return score
55 | else:
56 | if do_print:
57 | print(f"Incorrect answer {answer} | Ground truth: {ground_truth}")
58 | return format_score
59 |
--------------------------------------------------------------------------------
/verl/utils/tokenizer.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """Utils for tokenization."""
15 | import warnings
16 |
17 | __all__ = ['hf_tokenizer']
18 |
19 |
20 | def set_pad_token_id(tokenizer):
21 | """Set pad_token_id to eos_token_id if it is None.
22 |
23 | Args:
24 | tokenizer (transformers.PreTrainedTokenizer): The tokenizer to be set.
25 |
26 | """
27 | if tokenizer.pad_token_id is None:
28 | tokenizer.pad_token_id = tokenizer.eos_token_id
29 | warnings.warn(f'tokenizer.pad_token_id is None. Now set to {tokenizer.eos_token_id}')
30 | if tokenizer.pad_token is None:
31 | tokenizer.pad_token = tokenizer.eos_token
32 | warnings.warn(f'tokenizer.pad_token is None. Now set to {tokenizer.eos_token}')
33 |
34 |
35 | def hf_tokenizer(name_or_path, correct_pad_token=True, correct_gemma2=True, **kwargs):
36 | """Create a huggingface pretrained tokenizer.
37 |
38 | Args:
39 | name (str): The name of the tokenizer.
40 | correct_pad_token (bool): Whether to correct the pad token id.
41 | correct_gemma2 (bool): Whether to correct the gemma2 tokenizer.
42 | **kwargs: The keyword arguments for the tokenizer.
43 |
44 | Returns:
45 | transformers.PreTrainedTokenizer: The pretrained tokenizer.
46 |
47 | """
48 | from transformers import AutoTokenizer
49 | if correct_gemma2 and isinstance(name_or_path, str) and 'gemma-2-2b-it' in name_or_path:
50 | # the EOS token in gemma2 is ambiguious, which may worsen RL performance.
51 | # https://huggingface.co/google/gemma-2-2b-it/commit/17a01657f5c87135bcdd0ec7abb4b2dece04408a
52 | warnings.warn('Found gemma-2-2b-it tokenizer. Set eos_token and eos_token_id to and 107.')
53 | kwargs['eos_token'] = ''
54 | kwargs['eos_token_id'] = 107
55 | tokenizer = AutoTokenizer.from_pretrained(name_or_path, **kwargs)
56 | if correct_pad_token:
57 | set_pad_token_id(tokenizer)
58 | return tokenizer
--------------------------------------------------------------------------------
/verl/utils/torch_dtypes.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | Adapted from Cruise.
16 | """
17 |
18 | import torch
19 |
20 | from typing import Union
21 |
22 | HALF_LIST = [16, "16", "fp16", "float16"]
23 | FLOAT_LIST = [32, "32", "fp32", "float32"]
24 | BFLOAT_LIST = ["bf16", "bfloat16"]
25 |
26 |
27 | class PrecisionType(object):
28 | """Type of precision used.
29 |
30 | >>> PrecisionType.HALF == 16
31 | True
32 | >>> PrecisionType.HALF in (16, "16")
33 | True
34 | """
35 |
36 | HALF = "16"
37 | FLOAT = "32"
38 | FULL = "64"
39 | BFLOAT = "bf16"
40 | MIXED = "mixed"
41 |
42 | @staticmethod
43 | def supported_type(precision: Union[str, int]) -> bool:
44 | return any(x == precision for x in PrecisionType)
45 |
46 | @staticmethod
47 | def supported_types() -> list[str]:
48 | return [x.value for x in PrecisionType]
49 |
50 | @staticmethod
51 | def is_fp16(precision):
52 | return precision in HALF_LIST
53 |
54 | @staticmethod
55 | def is_fp32(precision):
56 | return precision in FLOAT_LIST
57 |
58 | @staticmethod
59 | def is_bf16(precision):
60 | return precision in BFLOAT_LIST
61 |
62 | @staticmethod
63 | def to_dtype(precision):
64 | if precision in HALF_LIST:
65 | return torch.float16
66 | elif precision in FLOAT_LIST:
67 | return torch.float32
68 | elif precision in BFLOAT_LIST:
69 | return torch.bfloat16
70 | else:
71 | raise RuntimeError(f"unexpected precision: {precision}")
72 |
73 | @staticmethod
74 | def to_str(precision):
75 | if precision == torch.float16:
76 | return 'fp16'
77 | elif precision == torch.float32:
78 | return 'fp32'
79 | elif precision == torch.bfloat16:
80 | return 'bf16'
81 | else:
82 | raise RuntimeError(f"unexpected precision: {precision}")
83 |
--------------------------------------------------------------------------------
/verl/utils/tracking.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | A unified tracking interface that supports logging data to different backend
16 | """
17 | import dataclasses
18 | from enum import Enum
19 | from functools import partial
20 | from pathlib import Path
21 | from typing import List, Union, Dict, Any
22 |
23 |
24 | class Tracking(object):
25 | supported_backend = ['wandb', 'mlflow', 'console']
26 |
27 | def __init__(self, project_name, experiment_name, default_backend: Union[str, List[str]] = 'console', config=None):
28 | if isinstance(default_backend, str):
29 | default_backend = [default_backend]
30 | for backend in default_backend:
31 | if backend == 'tracking':
32 | import warnings
33 | warnings.warn("`tracking` logger is deprecated. use `wandb` instead.", DeprecationWarning)
34 | else:
35 | assert backend in self.supported_backend, f'{backend} is not supported'
36 |
37 | self.logger = {}
38 |
39 | if 'tracking' in default_backend or 'wandb' in default_backend:
40 | import wandb
41 | import os
42 | WANDB_API_KEY = os.environ.get("WANDB_API_KEY", None)
43 | if WANDB_API_KEY:
44 | wandb.login(key=WANDB_API_KEY)
45 | wandb.init(project=project_name, name=experiment_name, config=config)
46 | self.logger['wandb'] = wandb
47 |
48 | if 'mlflow' in default_backend:
49 | import mlflow
50 | mlflow.start_run(run_name=experiment_name)
51 | mlflow.log_params(_compute_mlflow_params_from_objects(config))
52 | self.logger['mlflow'] = _MlflowLoggingAdapter()
53 |
54 | if 'console' in default_backend:
55 | from verl.utils.logger.aggregate_logger import LocalLogger
56 | self.console_logger = LocalLogger(print_to_console=True)
57 | self.logger['console'] = self.console_logger
58 |
59 | def log(self, data, step, backend=None):
60 | for default_backend, logger_instance in self.logger.items():
61 | if backend is None or default_backend in backend:
62 | logger_instance.log(data=data, step=step)
63 |
64 |
65 | class _MlflowLoggingAdapter:
66 |
67 | def log(self, data, step):
68 | import mlflow
69 | mlflow.log_metrics(metrics=data, step=step)
70 |
71 |
72 | def _compute_mlflow_params_from_objects(params) -> Dict[str, Any]:
73 | if params is None:
74 | return {}
75 |
76 | return _flatten_dict(_transform_params_to_json_serializable(params, convert_list_to_dict=True), sep='/')
77 |
78 |
79 | def _transform_params_to_json_serializable(x, convert_list_to_dict: bool):
80 | _transform = partial(_transform_params_to_json_serializable, convert_list_to_dict=convert_list_to_dict)
81 |
82 | if dataclasses.is_dataclass(x):
83 | return _transform(dataclasses.asdict(x))
84 | if isinstance(x, dict):
85 | return {k: _transform(v) for k, v in x.items()}
86 | if isinstance(x, list):
87 | if convert_list_to_dict:
88 | return {'list_len': len(x)} | {f'{i}': _transform(v) for i, v in enumerate(x)}
89 | else:
90 | return [_transform(v) for v in x]
91 | if isinstance(x, Path):
92 | return str(x)
93 | if isinstance(x, Enum):
94 | return x.value
95 |
96 | return x
97 |
98 |
99 | def _flatten_dict(raw: Dict[str, Any], *, sep: str) -> Dict[str, Any]:
100 | import pandas as pd
101 | ans = pd.json_normalize(raw, sep=sep).to_dict(orient='records')[0]
102 | assert isinstance(ans, dict)
103 | return ans
104 |
--------------------------------------------------------------------------------
/verl/version/version:
--------------------------------------------------------------------------------
1 | 0.1
--------------------------------------------------------------------------------
/verl/workers/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
--------------------------------------------------------------------------------
/verl/workers/actor/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from .base import BasePPOActor
16 | from .dp_actor import DataParallelPPOActor
17 |
18 | __all__ = ["BasePPOActor", "DataParallelPPOActor"]
19 |
--------------------------------------------------------------------------------
/verl/workers/actor/base.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | The base class for Actor
16 | """
17 | from abc import ABC, abstractmethod
18 | from typing import Iterable, Dict
19 |
20 | from verl import DataProto
21 | import torch
22 |
23 | __all__ = ['BasePPOActor']
24 |
25 |
26 | class BasePPOActor(ABC):
27 |
28 | def __init__(self, config):
29 | """The base class for PPO actor
30 |
31 | Args:
32 | config (DictConfig): a config passed to the PPOActor. We expect the type to be
33 | DictConfig (https://omegaconf.readthedocs.io/), but it can be any namedtuple in general.
34 | """
35 | super().__init__()
36 | self.config = config
37 |
38 | @abstractmethod
39 | def compute_log_prob(self, data: DataProto) -> torch.Tensor:
40 | """Compute logits given a batch of data.
41 |
42 | Args:
43 | data (DataProto): a batch of data represented by DataProto. It must contain key ```input_ids```,
44 | ```attention_mask``` and ```position_ids```.
45 |
46 | Returns:
47 | DataProto: a DataProto containing the key ```log_probs```
48 |
49 |
50 | """
51 | pass
52 |
53 | @abstractmethod
54 | def update_policy(self, data: DataProto) -> Dict:
55 | """Update the policy with an iterator of DataProto
56 |
57 | Args:
58 | data (DataProto): an iterator over the DataProto that returns by
59 | ```make_minibatch_iterator```
60 |
61 | Returns:
62 | Dict: a dictionary contains anything. Typically, it contains the statistics during updating the model
63 | such as ```loss```, ```grad_norm```, etc,.
64 |
65 | """
66 | pass
67 |
--------------------------------------------------------------------------------
/verl/workers/critic/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from .base import BasePPOCritic
16 | from .dp_critic import DataParallelPPOCritic
17 |
18 | __all__ = ["BasePPOCritic", "DataParallelPPOCritic"]
19 |
--------------------------------------------------------------------------------
/verl/workers/critic/base.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | Base class for a critic
16 | """
17 | from abc import ABC, abstractmethod
18 |
19 | import torch
20 |
21 | from verl import DataProto
22 |
23 | __all__ = ['BasePPOCritic']
24 |
25 |
26 | class BasePPOCritic(ABC):
27 |
28 | def __init__(self, config):
29 | super().__init__()
30 | self.config = config
31 |
32 | @abstractmethod
33 | def compute_values(self, data: DataProto) -> torch.Tensor:
34 | """Compute values"""
35 | pass
36 |
37 | @abstractmethod
38 | def update_critic(self, data: DataProto):
39 | """Update the critic"""
40 | pass
41 |
--------------------------------------------------------------------------------
/verl/workers/reward_model/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from .base import BasePPORewardModel
16 |
--------------------------------------------------------------------------------
/verl/workers/reward_model/base.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | The base class for reward model
16 | """
17 |
18 | from abc import ABC, abstractmethod
19 |
20 | from verl import DataProto
21 |
22 |
23 | class BasePPORewardModel(ABC):
24 |
25 | def __init__(self, config):
26 | self.config = config
27 |
28 | @abstractmethod
29 | def compute_reward(self, data: DataProto) -> DataProto:
30 | """Computing reward given input_ids. The transformers should output a tensor with shape
31 | [batch_size, sequence_length], and the value at [EOS] mask should be gathered.
32 |
33 | Args:
34 | data: must contain keys "input_ids", "attention_mask" and "position_ids".
35 | - input_ids: [batch_size, sequence_length]
36 | - attention_mask: [batch_size, sequence_length]
37 | - position_ids: [batch_size, sequence_length]
38 |
39 | Returns: a data pass protocol containing "reward". Only the [EOS] position contains the reward.
40 | Other position should have zero reward. Note that this may change in the future if we use
41 | dense reward. So, we leave the interface for general case.
42 | - reward: [batch_size, sequence_length].
43 |
44 | """
45 | pass
46 |
--------------------------------------------------------------------------------
/verl/workers/reward_model/megatron/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from .reward_model import MegatronRewardModel
16 |
--------------------------------------------------------------------------------
/verl/workers/rollout/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from .base import BaseRollout
16 | from .naive import NaiveRollout
17 | from .hf_rollout import HFRollout
18 |
19 | __all__ = ["BaseRollout", "NaiveRollout", "HFRollout"]
20 |
--------------------------------------------------------------------------------
/verl/workers/rollout/base.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from abc import ABC, abstractmethod
16 | from typing import Iterable, Union
17 |
18 | from verl import DataProto
19 |
20 | __all__ = ['BaseRollout']
21 |
22 |
23 | class BaseRollout(ABC):
24 |
25 | def __init__(self):
26 | """
27 |
28 | Args:
29 | dataloader: an Iterable of TensorDict that consistently generates prompts. Note that the dataloader
30 | should handle when the training stops.
31 | """
32 | super().__init__()
33 |
34 | @abstractmethod
35 | def generate_sequences(self, prompts: DataProto) -> DataProto:
36 | """Generate sequences"""
37 | pass
38 |
--------------------------------------------------------------------------------
/verl/workers/rollout/naive/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from .naive_rollout import NaiveRollout
16 |
--------------------------------------------------------------------------------
/verl/workers/rollout/vllm_rollout/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from .vllm_rollout import vLLMRollout
--------------------------------------------------------------------------------
/verl/workers/sharding_manager/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | from verl.utils.import_utils import is_vllm_available, is_megatron_core_available
16 |
17 | from .base import BaseShardingManager
18 | from .fsdp_ulysses import FSDPUlyssesShardingManager
19 |
20 | AllGatherPPModel = None
21 |
22 | if is_megatron_core_available() and is_vllm_available():
23 | from .megatron_vllm import AllGatherPPModel, MegatronVLLMShardingManager
24 | elif AllGatherPPModel is not None:
25 | pass
26 | else:
27 | AllGatherPPModel = None
28 | MegatronVLLMShardingManager = None
29 |
30 | if is_vllm_available():
31 | from .fsdp_vllm import FSDPVLLMShardingManager
32 | else:
33 | FSDPVLLMShardingManager = None
34 |
--------------------------------------------------------------------------------
/verl/workers/sharding_manager/base.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | Sharding manager to implement HybridEngine
16 | """
17 |
18 | from verl import DataProto
19 |
20 |
21 | class BaseShardingManager:
22 |
23 | def __enter__(self):
24 | pass
25 |
26 | def __exit__(self, exc_type, exc_value, traceback):
27 | pass
28 |
29 | def preprocess_data(self, data: DataProto) -> DataProto:
30 | return data
31 |
32 | def postprocess_data(self, data: DataProto) -> DataProto:
33 | return data
34 |
--------------------------------------------------------------------------------
/verl/workers/sharding_manager/fsdp_ulysses.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 Bytedance Ltd. and/or its affiliates
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | """
15 | Contains a resharding manager that binds weights from FSDP zero3 to XPerfGPT
16 | """
17 | from typing import Optional
18 | from .base import BaseShardingManager
19 |
20 | import random
21 | from torch.distributed.device_mesh import DeviceMesh
22 |
23 | from verl.utils.torch_functional import allgather_dict_tensors
24 | from verl.utils.ulysses import set_ulysses_sequence_parallel_group, get_ulysses_sequence_parallel_group
25 | import numpy as np
26 |
27 | import torch
28 | import torch.distributed
29 |
30 | from verl import DataProto
31 |
32 |
33 | class FSDPUlyssesShardingManager(BaseShardingManager):
34 | """
35 | Sharding manager to support data resharding when using FSDP + Ulysses
36 | """
37 |
38 | def __init__(self, device_mesh: DeviceMesh):
39 | super().__init__()
40 | self.device_mesh = device_mesh
41 | self.seed_offset = 12345
42 |
43 | def __enter__(self):
44 | if self.device_mesh is not None:
45 | # We have a global SP group
46 | # so we have to change to use model-specific sp group
47 | self.prev_sp_group = get_ulysses_sequence_parallel_group()
48 | set_ulysses_sequence_parallel_group(self.device_mesh['sp'].get_group())
49 | # TODO: check how to set seed for each model
50 |
51 | def __exit__(self, exc_type, exc_value, traceback):
52 | # restore random states
53 | if self.device_mesh is not None:
54 | # revert to previous sp group
55 | set_ulysses_sequence_parallel_group(self.prev_sp_group)
56 | # TODO: check how to set seed for each model
57 |
58 | def preprocess_data(self, data: DataProto) -> DataProto:
59 | """
60 | AllGather data from sp region
61 | This is because the data is first sharded along the FSDP dimension as we utilize the DP_COMPUTE
62 | In Ulysses, we need to make sure the same data is used across a SP group
63 | """
64 | if self.device_mesh is not None:
65 | sp_size = self.device_mesh['sp'].size()
66 | group = self.device_mesh['sp'].get_group()
67 |
68 | prev_device = data.batch.device
69 | data.batch = data.batch.cuda(device=torch.cuda.current_device())
70 | data.batch = allgather_dict_tensors(data.batch.contiguous(), size=sp_size, group=group, dim=0)
71 | data.batch = data.batch.to(prev_device)
72 | # all gather non_tensor_batch
73 | all_non_tensor_batch = [None for _ in range(sp_size)]
74 | torch.distributed.all_gather_object(all_non_tensor_batch, data.non_tensor_batch, group=group)
75 | data.non_tensor_batch = {
76 | k: np.concatenate([d[k] for d in all_non_tensor_batch]) for k in data.non_tensor_batch
77 | }
78 | return data
79 |
80 | def postprocess_data(self, data: DataProto) -> DataProto:
81 | """
82 | Split the data to follow FSDP partition
83 | """
84 | if self.device_mesh is not None:
85 | sp_size = self.device_mesh['sp'].size()
86 | sp_rank = self.device_mesh['sp'].get_local_rank()
87 | data = data.chunk(chunks=sp_size)[sp_rank]
88 | return data
--------------------------------------------------------------------------------