-
Notifications
You must be signed in to change notification settings - Fork 2.6k
GOLDTrainer VLM support #5461
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
Strongich
wants to merge
10
commits into
huggingface:main
Choose a base branch
from
Strongich:gold_vlm_support
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
GOLDTrainer VLM support #5461
Changes from 6 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
a1c3772
Add VLM support to GOLDTrainer (without vLLM yet)
Strongich a92473b
add vlm support with use_vllm=True
Strongich 23784b0
Add cross-architecture VLM distillation support to GOLDTrainer
Strongich 9a1f345
fix collator mutation bug and reject Liger kernel for VLMs
Strongich 606d68d
pass tokenizer instead of processing_class to the ULDLoss
Strongich 159e7a3
fix prompt_lengths split to use min instead of max after flush_left
Strongich bd820ad
fix prompt length split for JSD loss
Strongich 571099e
batch VLM vLLM generation across slices & fix VLM dataset columns str…
Strongich eaa258d
fix VLM data pipeline
Strongich 7c96055
Merge branch 'main' into gold_vlm_support
Strongich 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| # Copyright 2020-2026 The HuggingFace Team. All rights reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """ | ||
| GOLD VLM distillation on MMK12. | ||
|
|
||
| # Example 1 — Same-family distillation (SmolVLM-500M → SmolVLM-256M) | ||
| # Uses JSD loss. Same architecture and tokenizer, so standard distillation works directly. | ||
| # vLLM enabled for faster on-policy generation. | ||
| accelerate launch examples/scripts/gold_vlm.py \ | ||
| --student_model_name HuggingFaceTB/SmolVLM-256M-Instruct \ | ||
| --teacher_model_name HuggingFaceTB/SmolVLM-500M-Instruct \ | ||
| --lmbda 0.5 \ | ||
| --use_vllm \ | ||
| --vllm_mode colocate | ||
|
|
||
| # Example 2 — Cross-family distillation (Qwen2.5-VL-3B → SmolVLM-256M) | ||
| # Different architectures have incompatible tokenizers and image token formats, | ||
| # so ULD (Universal Logit Distillation) loss is required to align logits across vocabularies. | ||
| accelerate launch examples/scripts/gold_vlm.py \ | ||
| --student_model_name HuggingFaceTB/SmolVLM-256M-Instruct \ | ||
| --teacher_model_name Qwen/Qwen2.5-VL-3B-Instruct \ | ||
| --use_uld_loss \ | ||
| --lmbda 0.0 | ||
| """ | ||
|
|
||
| import argparse | ||
|
|
||
| import torch | ||
| from datasets import load_dataset | ||
| from peft import LoraConfig | ||
| from transformers import AutoModelForImageTextToText, AutoProcessor | ||
|
|
||
| from trl.experimental.gold import GOLDConfig, GOLDTrainer | ||
|
|
||
|
|
||
| SYSTEM_PROMPT = ( | ||
| "You are a helpful AI Assistant that provides well-reasoned and detailed responses. " | ||
| "You first think about the reasoning process as an internal monologue and then provide the user with the answer. " | ||
| "Respond in the following format: <think>\n...\n</think>\n<answer>\n...\n</answer>" | ||
| ) | ||
|
|
||
|
|
||
| def make_conversation(example): | ||
| """Convert MMK12 row into the chat format expected by TRL VLM trainers.""" | ||
| return { | ||
| "prompt": [ | ||
| { | ||
| "role": "system", | ||
| "content": [{"type": "text", "text": SYSTEM_PROMPT}], | ||
| }, | ||
| { | ||
| "role": "user", | ||
| "content": [ | ||
| {"type": "image"}, | ||
| {"type": "text", "text": example["question"]}, | ||
| ], | ||
| }, | ||
| ], | ||
| "completion": [ | ||
| { | ||
| "role": "assistant", | ||
| "content": [{"type": "text", "text": str(example["answer"])}], | ||
| }, | ||
| ], | ||
| "image": example["image"], | ||
| } | ||
|
|
||
|
|
||
| def filter_big_images(example): | ||
| image = example["image"] | ||
| return image.size[0] < 512 and image.size[1] < 512 | ||
|
|
||
|
|
||
| def convert_to_rgb(example): | ||
| image = example["image"] | ||
| if image.mode != "RGB": | ||
| image = image.convert("RGB") | ||
| example["image"] = image | ||
| return example | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| parser = argparse.ArgumentParser() | ||
| parser.add_argument("--student_model_name", type=str, default="HuggingFaceTB/SmolVLM-256M-Instruct") | ||
| parser.add_argument("--teacher_model_name", type=str, default="HuggingFaceTB/SmolVLM-500M-Instruct") | ||
| parser.add_argument("--use_uld_loss", action="store_true") | ||
| parser.add_argument("--lmbda", type=float, default=0.5) | ||
| parser.add_argument("--use_vllm", action="store_true") | ||
| parser.add_argument("--vllm_mode", type=str, default="colocate") | ||
| cli_args = parser.parse_args() | ||
|
|
||
| # ────────────────────────────────────────────── | ||
| # Models | ||
| # ────────────────────────────────────────────── | ||
| student_model = AutoModelForImageTextToText.from_pretrained(cli_args.student_model_name, dtype=torch.bfloat16) | ||
| teacher_model = AutoModelForImageTextToText.from_pretrained(cli_args.teacher_model_name, dtype=torch.bfloat16) | ||
|
|
||
| # Freeze everything except the language model head | ||
| for name, param in student_model.named_parameters(): | ||
| if "language_model" not in name: | ||
| param.requires_grad = False | ||
|
|
||
| processor = AutoProcessor.from_pretrained(cli_args.student_model_name, padding_side="left") | ||
|
|
||
| # toy example to fit small GPUs | ||
| peft_config = LoraConfig( | ||
| r=4, | ||
| lora_alpha=8, | ||
| lora_dropout=0.05, | ||
| target_modules=["q_proj"], | ||
| ) | ||
|
|
||
| # ────────────────────────────────────────────── | ||
| # Dataset | ||
| # ────────────────────────────────────────────── | ||
| dataset = load_dataset("FanqingM/MMK12", split="train[:5%]") | ||
| dataset = dataset.filter(filter_big_images) | ||
| dataset = dataset.map(convert_to_rgb) | ||
| dataset = dataset.map(make_conversation) | ||
|
|
||
| # ────────────────────────────────────────────── | ||
| # Training config | ||
| # ────────────────────────────────────────────── | ||
| args = GOLDConfig( | ||
| output_dir="gold-vlm-distillation", | ||
| # GOLD-specific | ||
| lmbda=cli_args.lmbda, | ||
| beta=0.5, | ||
| temperature=0.9, | ||
| max_completion_length=256, | ||
| teacher_model_name_or_path=cli_args.teacher_model_name, | ||
| num_generations=1, | ||
| use_uld_loss=cli_args.use_uld_loss, | ||
| # vLLM | ||
| use_vllm=cli_args.use_vllm, | ||
| vllm_mode=cli_args.vllm_mode, | ||
| vllm_gpu_memory_utilization=0.5, | ||
| vllm_max_model_length=8192, | ||
| # VLM image tokens expand during processing, so the default max_length (1024) is often too small. | ||
| # Which will lead to shifted_student_logits become an empty Tensor. | ||
| max_length=2048, | ||
| # Training schedule | ||
| per_device_train_batch_size=2, | ||
| gradient_accumulation_steps=4, | ||
| max_steps=100, | ||
| learning_rate=2e-5, | ||
| warmup_steps=10, | ||
| # Precision | ||
| bf16=True, | ||
| # Logging | ||
| logging_steps=1, | ||
| log_completions=True, | ||
| report_to="none", | ||
| ) | ||
|
|
||
| # ────────────────────────────────────────────── | ||
| # Trainer | ||
| # ────────────────────────────────────────────── | ||
| trainer = GOLDTrainer( | ||
| model=student_model, | ||
| teacher_model=teacher_model, | ||
| args=args, | ||
| train_dataset=dataset, | ||
| processing_class=processor, | ||
| peft_config=peft_config, | ||
| ) | ||
|
|
||
| trainer.train() | ||
| trainer.save_model(args.output_dir) | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Example script uses wrong dtype parameter name
Low Severity
AutoModelForImageTextToText.from_pretrainedis called withdtype=torch.bfloat16instead of the correcttorch_dtype=torch.bfloat16. Thedtypekwarg is not a recognized parameter forfrom_pretrained, so the models will silently load in their default precision (float32) instead of bfloat16, increasing memory usage and potentially causing dtype mismatches during training.Reviewed by Cursor Bugbot for commit 9a1f345. Configure here.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not a bug, torch_dtype is deprecated (everybody knows this warning)
Maybe I should add version checking, like here