-
Notifications
You must be signed in to change notification settings - Fork 3.7k
[5/n][trainer] feat: flowgrpo trainer #5951
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
zhtmike
wants to merge
15
commits into
verl-project:main
Choose a base branch
from
zhtmike:trainer-pr
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
e2067cc
add flowgrpo trainer
zhtmike f9db892
update testcase
zhtmike d8d7a8f
update comment
zhtmike e4330dc
fix metric & clean
zhtmike 54dd6c2
fix dataset
zhtmike 30a7365
fix dataset 2
zhtmike 096e165
drop untested scripted for now
zhtmike 8a0b3bf
Merge branch 'main' into trainer-pr
zhtmike c7f554d
fix bug
zhtmike cb46da5
clean
zhtmike 600593e
更新 qwenimage_ocr.py
zhtmike 475407f
Merge branch 'main' into trainer-pr
zhtmike 4e8b029
update script
zhtmike 002b0b6
Merge branch 'main' into trainer-pr
zhtmike 967e265
Merge branch 'main' into trainer-pr
zhtmike File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
104 changes: 104 additions & 0 deletions
104
examples/flowgrpo_trainer/data_process/qwenimage_ocr.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| # Copyright 2026 Bytedance Ltd. and/or its affiliates | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """ | ||
| Preprocess the OCR dataset to parquet format (for Qwen-Image training). | ||
| You can obtain the raw dataset from https://github.com/yifan123/flow_grpo/tree/main/dataset/ocr | ||
| """ | ||
|
|
||
| import argparse | ||
| import os | ||
|
|
||
| import datasets | ||
|
|
||
| from verl.utils.hdfs_io import copy, makedirs | ||
|
|
||
|
|
||
| def extract_solution(solution_str): | ||
| # The solution is stored in the format: 'The image displays "xxx".' | ||
| return solution_str.split('"')[1] | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| parser = argparse.ArgumentParser() | ||
| parser.add_argument("--local_dir", default=None) | ||
| parser.add_argument("--hdfs_dir", default=None) | ||
| parser.add_argument( | ||
| "--local_dataset_path", default="~/dataset/ocr/", help="The local path to the raw dataset, if it exists." | ||
| ) | ||
| parser.add_argument( | ||
| "--local_save_dir", default="~/data/ocr", help="The save directory for the preprocessed dataset." | ||
| ) | ||
|
|
||
| args = parser.parse_args() | ||
| if args.local_dataset_path is not None: | ||
| local_dataset_path = os.path.expanduser(args.local_dataset_path) | ||
|
|
||
| data_source = "flow_grpo/ocr" | ||
|
|
||
| if local_dataset_path is not None: | ||
| dataset = datasets.load_dataset(local_dataset_path) | ||
| else: | ||
| raise NotImplementedError( | ||
| "It is not existed in huggingface hub. " | ||
| "Please get dataset from https://github.com/yifan123/flow_grpo/tree/main/dataset/ocr" | ||
| ) | ||
|
|
||
| train_dataset = dataset["train"] | ||
| test_dataset = dataset["test"] | ||
|
|
||
| system_prompt = ( | ||
| "Describe the image by detailing the color, shape, size, " | ||
| "texture, quantity, text, spatial relationships of the objects and background:" | ||
| ) | ||
| negative_user_prompt = " " | ||
|
|
||
| def make_map_fn(split): | ||
| def process_fn(example, idx): | ||
| text = example.pop("text") | ||
| solution = extract_solution(text) | ||
| data = { | ||
| "data_source": data_source, | ||
| "prompt": [ | ||
| {"role": "system", "content": system_prompt}, | ||
| {"role": "user", "content": text}, | ||
| ], | ||
| "negative_prompt": [ | ||
| {"role": "system", "content": system_prompt}, | ||
| {"role": "user", "content": negative_user_prompt}, | ||
| ], | ||
| "ability": "ocr", | ||
| "reward_model": {"style": "model", "ground_truth": solution}, | ||
| "extra_info": {"split": split, "index": idx}, | ||
| } | ||
| return data | ||
|
|
||
| return process_fn | ||
|
|
||
| train_dataset = train_dataset.map(function=make_map_fn("train"), with_indices=True) | ||
| test_dataset = test_dataset.map(function=make_map_fn("test"), with_indices=True) | ||
|
|
||
| hdfs_dir = args.hdfs_dir | ||
| local_save_dir = args.local_dir | ||
| if local_save_dir is not None: | ||
| print("Warning: Argument 'local_dir' is deprecated. Please use 'local_save_dir' instead.") | ||
| else: | ||
| local_save_dir = args.local_save_dir | ||
|
|
||
| local_save_dir = os.path.expanduser(local_save_dir) | ||
| train_dataset.to_parquet(os.path.join(local_save_dir, "train.parquet")) | ||
| test_dataset.to_parquet(os.path.join(local_save_dir, "test.parquet")) | ||
|
|
||
| if hdfs_dir is not None: | ||
| makedirs(hdfs_dir) | ||
| copy(src=local_save_dir, dst=hdfs_dir) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| # Qwen-Image lora RL, vllm_omni rollout | ||
| set -x | ||
|
|
||
| ocr_train_path=$HOME/data/ocr/train.parquet | ||
| ocr_test_path=$HOME/data/ocr/test.parquet | ||
|
|
||
| ENGINE=vllm_omni | ||
| REWARD_ENGINE=vllm | ||
|
|
||
| reward_path=examples/flowgrpo_trainer/reward_fn.py | ||
| reward_model_name=$HOME/models/Qwen/Qwen3-VL-8B-Instruct | ||
|
|
||
|
|
||
| python3 -m verl.trainer.main_flowgrpo \ | ||
| algorithm.adv_estimator=flow_grpo \ | ||
| data.train_files=$ocr_train_path \ | ||
| data.val_files=$ocr_test_path \ | ||
| data.train_batch_size=32 \ | ||
| data.max_prompt_length=256 \ | ||
| actor_rollout_ref.model.path=$HOME/models/Qwen/Qwen-Image \ | ||
| actor_rollout_ref.model.tokenizer_path=$HOME/models/Qwen/Qwen-Image/tokenizer \ | ||
| actor_rollout_ref.model.external_lib="examples.flowgrpo_trainer.diffusers.qwen_image" \ | ||
| actor_rollout_ref.model.lora_rank=64 \ | ||
| actor_rollout_ref.model.lora_alpha=128 \ | ||
| actor_rollout_ref.model.target_modules="['to_q','to_k','to_v','to_out.0','add_q_proj','add_k_proj','add_v_proj','to_add_out','img_mlp.net.0.proj','img_mlp.net.2','txt_mlp.net.0.proj','txt_mlp.net.2']" \ | ||
| actor_rollout_ref.actor.optim.lr=3e-4 \ | ||
| actor_rollout_ref.actor.optim.weight_decay=0.0001 \ | ||
| actor_rollout_ref.actor.ppo_mini_batch_size=16 \ | ||
| actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=16 \ | ||
| actor_rollout_ref.actor.fsdp_config.param_offload=True \ | ||
| actor_rollout_ref.actor.fsdp_config.optimizer_offload=True \ | ||
| actor_rollout_ref.actor.fsdp_config.model_dtype=bfloat16 \ | ||
| actor_rollout_ref.actor.policy_loss.loss_mode=flow_grpo \ | ||
| actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=32 \ | ||
| actor_rollout_ref.rollout.tensor_model_parallel_size=1 \ | ||
| actor_rollout_ref.rollout.name=$ENGINE \ | ||
| actor_rollout_ref.rollout.n=16 \ | ||
| actor_rollout_ref.rollout.agent.default_agent_loop=diffusion_single_turn_agent \ | ||
| actor_rollout_ref.rollout.agent.num_workers=4 \ | ||
| actor_rollout_ref.rollout.load_format=safetensors \ | ||
| actor_rollout_ref.rollout.layered_summon=True \ | ||
| actor_rollout_ref.rollout.val_kwargs.num_inference_steps=50 \ | ||
| +actor_rollout_ref.rollout.extra_configs.true_cfg_scale=4.0 \ | ||
| +actor_rollout_ref.rollout.extra_configs.noise_level=1.2 \ | ||
| +actor_rollout_ref.rollout.extra_configs.sde_type="sde" \ | ||
| +actor_rollout_ref.rollout.extra_configs.sde_window_size=2 \ | ||
| +actor_rollout_ref.rollout.extra_configs.sde_window_range="[0,5]" \ | ||
| +actor_rollout_ref.rollout.extra_configs.max_sequence_length=256 \ | ||
| +actor_rollout_ref.rollout.val_kwargs.extra_configs.noise_level=0.0 \ | ||
| +actor_rollout_ref.rollout.engine_kwargs.vllm_omni.custom_pipeline=examples.flowgrpo_trainer.vllm_omni.pipeline_qwenimage.QwenImagePipelineWithLogProb \ | ||
| actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=32 \ | ||
| reward.num_workers=4 \ | ||
| reward.reward_manager.name=visual \ | ||
| reward.reward_model.enable=True \ | ||
| reward.reward_model.model_path=$reward_model_name \ | ||
| reward.reward_model.rollout.name=$REWARD_ENGINE \ | ||
| reward.reward_model.rollout.tensor_model_parallel_size=4 \ | ||
| reward.custom_reward_function.path=$reward_path \ | ||
| reward.custom_reward_function.name=compute_score_ocr \ | ||
| trainer.use_legacy_worker_impl=disable \ | ||
| trainer.logger='["console", "wandb"]' \ | ||
| trainer.project_name=flow_grpo \ | ||
| trainer.experiment_name=qwen_image_ocr_lora \ | ||
| trainer.log_val_generations=8 \ | ||
| trainer.val_before_train=False \ | ||
| trainer.n_gpus_per_node=4 \ | ||
| trainer.nnodes=1 \ | ||
| trainer.save_freq=30 \ | ||
| trainer.test_freq=30 \ | ||
| trainer.total_epochs=15 \ | ||
| trainer.total_training_steps=300 $@ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| # Copyright 2026 Bytedance Ltd. and/or its affiliates | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """ | ||
| Create a small synthetic parquet dataset for FlowGRPO diffusion e2e testing. | ||
|
|
||
| The dataset uses the jpeg_compressibility reward (a self-contained rule-based | ||
| reward that needs no external reward model) so the e2e test can run without | ||
| spinning up a separate vLLM reward server. | ||
| """ | ||
|
|
||
| import argparse | ||
| import os | ||
|
|
||
| import pandas as pd | ||
|
|
||
| SYSTEM_PROMPT = ( | ||
| "Describe the image by detailing the color, shape, size, " | ||
| "texture, quantity, text, spatial relationships of the objects and background:" | ||
| ) | ||
|
|
||
| USER_PROMPTS = [ | ||
| "A red circle on a white background", | ||
| "A blue square on a black background", | ||
| "A green triangle next to an orange rectangle", | ||
| "The word HELLO written in bold letters", | ||
| "A yellow star above a purple crescent moon", | ||
| "Two overlapping circles, one red and one blue", | ||
| "A gradient from dark blue to light blue", | ||
| "A checkerboard pattern of black and white squares", | ||
| ] | ||
|
|
||
|
|
||
| def build_rows(split: str, n: int): | ||
| rows = [] | ||
| for i in range(n): | ||
| prompt_text = USER_PROMPTS[i % len(USER_PROMPTS)] | ||
| rows.append( | ||
| { | ||
| "data_source": "jpeg_compressibility", | ||
| "prompt": [ | ||
| {"role": "system", "content": SYSTEM_PROMPT}, | ||
| {"role": "user", "content": prompt_text}, | ||
| ], | ||
| "negative_prompt": [ | ||
| {"role": "system", "content": SYSTEM_PROMPT}, | ||
| {"role": "user", "content": " "}, | ||
| ], | ||
| "reward_model": {"style": "rule", "ground_truth": ""}, | ||
| "extra_info": {"split": split, "index": i}, | ||
| } | ||
| ) | ||
| return rows | ||
|
|
||
|
|
||
| def main(): | ||
| parser = argparse.ArgumentParser(description="Generate dummy diffusion parquet data for e2e testing") | ||
| parser.add_argument( | ||
| "--local_save_dir", | ||
| default=os.path.expanduser("~/data/dummy_diffusion"), | ||
| help="Directory to write train.parquet and test.parquet", | ||
| ) | ||
| parser.add_argument("--train_size", type=int, default=32, help="Number of training samples") | ||
| parser.add_argument("--val_size", type=int, default=8, help="Number of validation samples") | ||
| args = parser.parse_args() | ||
|
|
||
| os.makedirs(args.local_save_dir, exist_ok=True) | ||
|
|
||
| train_df = pd.DataFrame(build_rows("train", args.train_size)) | ||
| val_df = pd.DataFrame(build_rows("test", args.val_size)) | ||
|
|
||
| train_path = os.path.join(args.local_save_dir, "train.parquet") | ||
| val_path = os.path.join(args.local_save_dir, "test.parquet") | ||
|
|
||
| train_df.to_parquet(train_path) | ||
| val_df.to_parquet(val_path) | ||
|
|
||
| print(f"Wrote {len(train_df)} train samples to {train_path}") | ||
| print(f"Wrote {len(val_df)} val samples to {val_path}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.