DFlash VLM training support with SGLang backend
Summary
This PR extends DFlash speculative decoding training to support Vision-Language Models (VLMs),
with Qwen3.5-VL as the primary validated target. It adds multimodal data ingestion,
SGLang multimodal request construction using MRotaryEmbedding, configurable weight key
paths for VLM architectures, and several correctness fixes to the base training loop.
Mixed Text + VLM Training
This PR supports training on a mixture of text-only and vision-language samples within
the same run. When --is-vlm is set and the dataset contains samples where image is
None, those samples are processed as text-only with empty tensor placeholders for
pixel_values/image_grid_thw to maintain a consistent HuggingFace Arrow schema across
parallel preprocessing shards.
--batch-size 1is required for VLM and mixed training.
VlmDataCollatorWithPaddingenforcesbatch_size=1with an assertion. Each step is either a single VLM sample (with pixel values forwarded to SGLang) or a single text sample (pixel values areNone, falls back to the text-only SGLang path). Batched multi-sample VLM inference is left as future work.
Changes
scripts/train_dflash.py
- Add
--embed-key/--lm-head-keyto configure weight key paths; VLMs typically usemodel.language_model.embed_tokens.weightinstead of the LLM default - Load
AutoProcessorwhen--is-vlmis set; thread it throughbuild_dataloader
specforge/data/preprocessing.py
- Fix multi-turn image injection: images are now attached only to the first user turn. Previously every user turn received the image, breaking multi-turn conversation formatting. Currently we do not support multiple images in one data item.
- Remove the default system prompt prepended to all VLM conversations; the model's own chat template is responsible for system prompts.
- Fix
AttributeError: 'NoneType'.startswithcrash: samples withimage=Noneare now handled gracefully — processed as text-only with empty tensor placeholders forpixel_values/image_grid_thwto keep the HF Arrow schema consistent across shards.
specforge/data/utils.py
VlmDataCollatorWithPadding: enforcebatch_size=1with an assertion; passpixel_valuesdirectly for VLM samples andNonefor text-only samples so the training loop falls back to the text-only SGLang path.
specforge/modeling/target/dflash_target_model.py
- Add
_build_vlm_reqs()to construct SGLangReqobjects with fullMultimodalInputs:- Slices
pixel_valuesper sample usingimage_grid_thwpatch counts (t×h×w) - Handles both single-image (1D) and multi-image (2D)
image_grid_thwtensors - Computes mrope positions via
MRotaryEmbedding.get_rope_indexusing the auto-detectedvlm_model_type - Pads input tokens via
MultiModalityDataPaddingPatternMultimodalTokens
- Slices
- Lift
RadixCachecreation out of_extend()into__init__asself.dummy_tree_cacheto avoid re-allocating the cache on every forward pass - Update
generate_dflash_data()to branch onis_vlm_batchand dispatch to_build_vlm_reqs; refactor the text-only path to no longer maintain adata_cache - Add
set_dflash_layers_to_capture()dispatch alongside the existingset_eagle3_layers_to_capture()inset_capture_layers() - Update
HFDFlashTargetModel.generate_dflash_data()to forwardpixel_values/image_grid_thwto the HF model viamodel_kwargs
specforge/modeling/target/target_utils.py
- Fall back to
text_configforvocab_size,hidden_size, andpad_token_idwhen the top-level VLM config does not expose them directly
References
- #495 — prior VLM preprocessing work this PR builds on
- #496 — sglang 0.5.9 upgrade and Qwen3.5 Eagle3 support (merged);
patch.pyandmodel_runner.pychanges in this PR are a subset of that work - https://github.com/sgl-project/sglang/pull/16818
- We used this SGLang for training backend: https://github.com/Mandy3311/sglang-speculative-train
Summary of Changes
Hello, I'm Gemini Code Assist[^1]! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request significantly enhances the DFlash speculative decoding training framework by integrating robust support for Vision-Language Models (VLMs). It allows for seamless training on datasets containing both text-only and multimodal samples, addressing critical aspects of VLM data handling, such as image injection in conversations and consistent data schema management. The changes also include architectural adaptations for VLM-specific model configurations and optimized SGLang backend interactions for multimodal inputs, laying the groundwork for more versatile and efficient VLM training.
Highlights
- VLM Training Support: Introduced comprehensive support for Vision-Language Model (VLM) training within DFlash speculative decoding, with Qwen3.5-VL as a primary validated target.
- Mixed Text + VLM Training: Enabled mixed training on both text-only and multimodal (vision-language) samples within the same run, gracefully handling text-only samples with empty tensor placeholders for pixel values.
- Configurable Weight Key Paths: Added configurable
embed-keyandlm-head-keyarguments totrain_dflash.pyto support diverse VLM architectures' weight key paths (e.g.,model.language_model.embed_tokens.weight). - Multi-turn Image Injection Fix: Implemented a fix in
preprocessing.pyto ensure images are injected only into the first user turn of multi-turn VLM conversations, preventing incorrect formatting. - Batch Size Enforcement: Enforced
batch_size=1for VLM and mixed training inVlmDataCollatorWithPaddingdue to current limitations in batched multi-sample VLM inference. - SGLang Multimodal Request Construction: Developed
_build_vlm_reqs()indflash_target_model.pyto construct SGLangReqobjects withMultimodalInputs, handling image slicing, mrope positions viaMRotaryEmbedding, and multimodal token padding. - RadixCache Optimization: Refactored
RadixCachecreation inSGLangDFlashTargetModelto initialize it once in__init__asself.dummy_tree_cache, avoiding re-allocation on every forward pass. - Dynamic Data Processing: Updated
generate_dflash_data()to dynamically dispatch between VLM and text-only processing paths based on the presence ofpixel_valuesandimage_grid_thw. - VLM Config Attribute Fallback: Implemented fallback logic in
target_utils.pyto retrievevocab_size,hidden_size, andpad_token_idfromtext_configwhen not directly available in the VLM's top-level configuration.
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.
Changelog
- scripts/train_dflash.py
- Added
datasets.load_from_diskimport andloggingconfiguration for SGLang. - Introduced command-line arguments:
--embed-key,--lm-head-key,--is-vlm,--min-pixels, and--max-pixelsfor VLM configuration. - Refactored
_load_raw_datasetto handle both directory and JSONL data paths. - Modified
build_dataloaderto accept and pass aprocessorargument, andis_vlmflag to dataset building. - Updated checkpoint loading logic to initialize
start_epochandglobal_stepmore robustly. - Integrated
AutoProcessorloading when--is-vlmis enabled, usingmin_pixelsandmax_pixelsarguments. - Passed
processortobuild_dataloaderand used configurableembed_key/lm_head_keyforTargetEmbeddingsAndHeadinitialization. - Adjusted
generate_dflash_datacall to passpixel_valuesandimage_grid_thwconditionally based on VLM training.
- Added
- specforge/data/preprocessing.py
- Removed the default system prompt prepended to all VLM conversations.
- Implemented logic to inject images only into the first user turn in multi-turn conversations, preventing repeated image attachments.
- Added handling for
image=Nonesamples, processing them as text-only with empty tensor placeholders for pixel values and image grid information to maintain schema consistency.
- specforge/data/utils.py
- Enforced
batch_size=1forVlmDataCollatorWithPaddingwith an assertion. - Modified
__call__to conditionally includepixel_valuesandimage_grid_thwin the batch based on their presence and length, supporting text-only samples.
- Enforced
- specforge/modeling/target/dflash_target_model.py
- Imported various SGLang multimodal utilities, including
MRotaryEmbedding,MultimodalDataItem, andMultimodalInputs. - Added
_init_vlm_attributesmethod to detect and cache VLM-specific token IDs and vision configuration from the HuggingFace config. - Moved
RadixCacheinitialization to__init__asself.dummy_tree_cacheto prevent re-allocation on every forward pass. - Introduced
_build_vlm_reqsto construct SGLangReqobjects for VLM inputs, including slicingpixel_values, computing mrope positions viaMRotaryEmbedding, and multimodal token padding. - Updated
set_capture_layersto dispatch toset_dflash_layers_to_captureorset_eagle3_layers_to_capture. - Refactored
_extendto useself.dummy_tree_cacheand updatedmodel_runner.forwardcall to retrievelogits_output. - Modified
generate_dflash_datato branch based onis_vlm_batchand use_build_vlm_reqsfor VLM inputs, or a simplified path for text-only inputs. - Updated
HFDFlashTargetModel.generate_dflash_datato accept and forwardpixel_valuesandimage_grid_thwviamodel_kwargsto the underlying HuggingFace model. - Removed
enable_piecewise_cuda_graphfrom kwargs for SGLang backend initialization.
- Imported various SGLang multimodal utilities, including
- specforge/modeling/target/sglang_backend/model_runner.py
- Removed unnecessary debug print statements related to parallel sizes during model initialization.
- specforge/modeling/target/sglang_backend/patch.py
- Corrected a descriptive comment in
initialize_model_parallelregarding pipeline model-parallel groups from[b1, g3, g5, g7]to[g1, g3, g5, g7].
- Corrected a descriptive comment in
- specforge/modeling/target/target_utils.py
- Added logic in
from_pretrainedto fall back toconfig.text_configforvocab_size,hidden_size, andpad_token_idif they are not directly present in the main model configuration.
- Added logic in
Activity
- No specific human activity (comments, reviews, or progress updates) was provided in the context.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in pull request comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with :thumbsup: and :thumbsdown: on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
[^1]: Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.
Hi @Mandy3311 can you help to resolve the conflict?
Hi @Mandy3311 can you help to resolve the conflict?
@Mandy3311 i have helped to resolve the conflict, @xiaomin-D can you help to review this PR?
@Mandy3311 i have helped to resolve the conflict, @xiaomin-D can you help to review this PR?
@Mandy3311 i have helped to resolve the conflict, @xiaomin-D can you help to review this PR? ok~
@Mandy3311 i have helped to resolve the conflict, @xiaomin-D can you help to review this PR? ok~
Thanks @FrankLeeeee ! Appreciate the help. @xiaomin-D Let me know if there are any questions during the review🙏
Thanks @FrankLeeeee ! Appreciate the help. @xiaomin-D Let me know if there are any questions during the review🙏
@Mandy3311 Hello, I was wondering if you have any test results for DFlash specifically on Qwen-VL?
@Mandy3311 Hello, I was wondering if you have any test results for DFlash specifically on Qwen-VL?
Thanks @FrankLeeeee ! Appreciate the help. @xiaomin-D Let me know if there are any questions during the review🙏
Thanks for the PR! Could you share training loss / accuracy curves and inference speedup benchmarks (e.g. acceptance rate, tokens/s) for Qwen-VL?
Thanks @FrankLeeeee ! Appreciate the help. @xiaomin-D Let me know if there are any questions during the review🙏
Thanks for the PR! Could you share training loss / accuracy curves and inference speedup benchmarks (e.g. acceptance rate, tokens/s) for Qwen-VL?
@xiaomin-D Thanks for the review! I'm working through your comments now and will push updates soon.
@fousdfrf @xiaomin-D About the training results, we ran a preliminary experiment with Qwen3.5-4B trained on 1,000 images sampled from the_cauldron (https://huggingface.co/datasets/HuggingFaceM4/the_cauldron), for output length 128 we got acceptance length at about 6. However, we observed that the Qwen3.5 outputs are not stable enough to give reliable training results. We are currently running a more rigorous experiment with Qwen3-VL-32B-Instruct, but due to resource constraints we are not yet able to share full results. We will update this PR with quantitative results once the training completes.
@xiaomin-D Thanks for the review! I'm working through your comments now and will push updates soon.
@fousdfrf @xiaomin-D About the training results, we ran a preliminary experiment with Qwen3.5-4B trained on 1,000 images sampled from the_cauldron (https://huggingface.co/datasets/HuggingFaceM4/the_cauldron), for output length 128 we got acceptance length at about 6. However, we observed that the Qwen3.5 outputs are not stable enough to give reliable training results. We are currently running a more rigorous experiment with Qwen3-VL-32B-Instruct, but due to resource constraints we are not yet able to share full results. We will update this PR with quantitative results once the training completes.
Hi @xiaomin-D, I've addressed all the comments and conflicts. Could you take another look? Thanks!
Hi @xiaomin-D, I've addressed all the comments and conflicts. Could you take another look? Thanks!
Hi @xiaomin-D, I've addressed all the comments and conflicts. Could you take another look? Thanks!
LGTM! Thanks for the quick fixes. A few minor nits remaining (commented-out code cleanup, unused mrope_interleaved) — happy to approve, these can be addressed in a follow-up. @FrankLeeeee @Mandy3311
Hi @xiaomin-D, I've addressed all the comments and conflicts. Could you take another look? Thanks!
LGTM! Thanks for the quick fixes. A few minor nits remaining (commented-out code cleanup, unused mrope_interleaved) — happy to approve, these can be addressed in a follow-up. @FrankLeeeee @Mandy3311
@xiaomin-D I have removed the unused system_prompt and commented-out code. Could you point out which mrope_interleaved you are referring to?