|
| 1 | +# Copyright 2020-2025 The HuggingFace Team. All rights reserved. |
| 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 | +pip install math_verify |
| 17 | +
|
| 18 | +accelerate launch \ |
| 19 | + --config_file=examples/accelerate_configs/deepspeed_zero3.yaml \ |
| 20 | + examples/scripts/grpo_vlm.py \ |
| 21 | + --model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \ |
| 22 | + --output_dir grpo-Qwen2.5-VL-3B-Instruct \ |
| 23 | + --learning_rate 1e-5 \ |
| 24 | + --gradient_checkpointing \ |
| 25 | + --torch_dtype bfloat16 \ |
| 26 | + --max_prompt_length 2048 \ |
| 27 | + --max_completion_length 1024 \ |
| 28 | + --use_vllm \ |
| 29 | + --vllm_mode colocate \ |
| 30 | + --use_peft \ |
| 31 | + --lora_target_modules "q_proj", "v_proj" \ |
| 32 | + --log_completions |
| 33 | +""" |
| 34 | + |
| 35 | +import torch |
| 36 | +from datasets import load_dataset |
| 37 | +from latex2sympy2_extended import NormalizationConfig |
| 38 | +from math_verify import LatexExtractionConfig, parse, verify |
| 39 | + |
| 40 | +from trl import ( |
| 41 | + GRPOConfig, |
| 42 | + GRPOTrainer, |
| 43 | + ModelConfig, |
| 44 | + ScriptArguments, |
| 45 | + TrlParser, |
| 46 | + get_kbit_device_map, |
| 47 | + get_peft_config, |
| 48 | + get_quantization_config, |
| 49 | +) |
| 50 | +from trl.rewards import think_format_reward |
| 51 | + |
| 52 | + |
| 53 | +if __name__ == "__main__": |
| 54 | + parser = TrlParser((ScriptArguments, GRPOConfig, ModelConfig)) |
| 55 | + script_args, training_args, model_args = parser.parse_args_and_config() |
| 56 | + ################ |
| 57 | + # Model & Processor |
| 58 | + ################ |
| 59 | + torch_dtype = ( |
| 60 | + model_args.torch_dtype if model_args.torch_dtype in ["auto", None] else getattr(torch, model_args.torch_dtype) |
| 61 | + ) |
| 62 | + quantization_config = get_quantization_config(model_args) |
| 63 | + model_kwargs = dict( |
| 64 | + revision=model_args.model_revision, |
| 65 | + attn_implementation=model_args.attn_implementation, |
| 66 | + torch_dtype=torch_dtype, |
| 67 | + device_map=get_kbit_device_map() if quantization_config is not None else None, |
| 68 | + quantization_config=quantization_config, |
| 69 | + ) |
| 70 | + |
| 71 | + ################ |
| 72 | + # Dataset |
| 73 | + ################ |
| 74 | + dataset = load_dataset("lmms-lab/multimodal-open-r1-8k-verified", split="train") |
| 75 | + dataset = dataset.train_test_split(test_size=100, seed=42) |
| 76 | + |
| 77 | + SYSTEM_PROMPT = ( |
| 78 | + "A conversation between user and assistant. The user asks a question, and the assistant solves it. The " |
| 79 | + "assistant first thinks about the reasoning process in the mind and then provides the user with the answer. " |
| 80 | + "The reasoning process and answer are enclosed within <think></think> tags, i.e., <think>\nThis is my " |
| 81 | + "reasoning.\n</think>\nThis is my answer." |
| 82 | + ) |
| 83 | + |
| 84 | + def make_conversation(example): |
| 85 | + prompt = [ |
| 86 | + {"role": "system", "content": SYSTEM_PROMPT}, |
| 87 | + {"role": "user", "content": example["problem"]}, |
| 88 | + ] |
| 89 | + return {"prompt": prompt} |
| 90 | + |
| 91 | + dataset = dataset.map(make_conversation) |
| 92 | + |
| 93 | + # Filter have big images |
| 94 | + def filter_big_images(example): |
| 95 | + image = example["image"] |
| 96 | + return image.size[0] < 512 and image.size[1] < 512 |
| 97 | + |
| 98 | + dataset = dataset.filter(filter_big_images) |
| 99 | + |
| 100 | + train_dataset = dataset["train"] |
| 101 | + eval_dataset = dataset["test"] if training_args.eval_strategy != "no" else None |
| 102 | + |
| 103 | + ################ |
| 104 | + # Reward Function for Training |
| 105 | + ################ |
| 106 | + def accuracy_reward(completions, solution: list[str], **kwargs): |
| 107 | + """Reward function that checks if the completion matches the ground truth. |
| 108 | + - If both gold and prediction are parseable → use math verification. |
| 109 | + - If not parseable → compare as normalized text. |
| 110 | + """ |
| 111 | + rewards = [] |
| 112 | + contents = [completion[0]["content"] for completion in completions] |
| 113 | + for content, sol in zip(contents, solution): |
| 114 | + try: |
| 115 | + gold_parsed = parse(sol, extraction_mode="first_match") |
| 116 | + except Exception: |
| 117 | + gold_parsed = [] |
| 118 | + |
| 119 | + if len(gold_parsed) != 0: |
| 120 | + # Try parsing predicted answer too |
| 121 | + try: |
| 122 | + answer_parsed = parse( |
| 123 | + content, |
| 124 | + extraction_config=[ |
| 125 | + LatexExtractionConfig( |
| 126 | + normalization_config=NormalizationConfig( |
| 127 | + nits=False, |
| 128 | + malformed_operators=False, |
| 129 | + basic_latex=True, |
| 130 | + boxed="all", |
| 131 | + units=True, |
| 132 | + ), |
| 133 | + boxed_match_priority=0, |
| 134 | + try_extract_without_anchor=False, |
| 135 | + ) |
| 136 | + ], |
| 137 | + extraction_mode="first_match", |
| 138 | + ) |
| 139 | + reward = float(verify(gold_parsed, answer_parsed)) |
| 140 | + except Exception as e: |
| 141 | + print(f"verify failed: {e}, answer: {content}, gold: {sol}") |
| 142 | + reward = None |
| 143 | + else: |
| 144 | + # fallback to text match |
| 145 | + reward = float(content.strip().lower() == sol.strip().lower()) |
| 146 | + |
| 147 | + rewards.append(reward) |
| 148 | + |
| 149 | + return rewards |
| 150 | + |
| 151 | + ################ |
| 152 | + # Training |
| 153 | + ################ |
| 154 | + trainer = GRPOTrainer( |
| 155 | + model=model_args.model_name_or_path, |
| 156 | + args=training_args, |
| 157 | + reward_funcs=[think_format_reward, accuracy_reward], |
| 158 | + train_dataset=train_dataset, |
| 159 | + eval_dataset=eval_dataset, |
| 160 | + peft_config=get_peft_config(model_args), |
| 161 | + ) |
| 162 | + |
| 163 | + trainer.train() |
| 164 | + |
| 165 | + # Save and push to hub |
| 166 | + trainer.save_model(training_args.output_dir) |
| 167 | + if training_args.push_to_hub: |
| 168 | + trainer.push_to_hub(dataset_name=script_args.dataset_name) |
0 commit comments